package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.response.ContinueInfo;
import com.xmy.cultivate.entity.response.PracticePlanStaff;
import com.xmy.cultivate.respons.RenewHistoryData;
import com.xmy.cultivate.entity.response.YearAndQuarter;
import com.xmy.cultivate.entity.views.*;
import com.xmy.cultivate.exception.CommonException;
import com.xmy.cultivate.mapper.*;
import com.xmy.cultivate.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 续班表 服务实现类
 * </p>
 *
 * @author min
 * @since 2022-08-23
 */
@Service
public class RenewClassServiceImpl extends ServiceImpl<RenewClassMapper, RenewClass> implements IRenewClassService {

    @Autowired
    RenewClassMapper renewClassMapper;

    @Autowired
    RenewDataMapper renewDataMapper;

    @Autowired
    TrackMapper trackMapper;

    @Autowired
    TrackDetailMapper trackDetailMapper;


    @Autowired
    @Lazy
    IQuarterService iQuarterService;

    @Autowired
    @Lazy
    OrderDetailMapper orderDetailMapper;

    @Autowired
    GradeMapper gradeMapper;

    @Autowired
    IStudentGradeService iStudentGradeService;

    @Autowired
    IGradeService iGradeService;

    @Autowired
    IStaffService iStaffService;

    @Autowired
    TeacherContinueInfoMapper teacherContinueInfoMapper;

    @Autowired
    ITrackMarketService iTrackMarketService;

    @Autowired
    TrackMarketMapper trackMarketMapper;

    @Autowired
    ISchoolQuarterService iSchoolQuarterService;

    @Autowired
    OrganizationDepartmentPrincipalMapper organizationDepartmentPrincipalMapper;

    /**
     * @param schoolIdList
     * @param SubjectsId
     * @param YearPart
     * @param QuarterNum
     * @param TeacherName
     * @param StartDate
     * @param EndDate
     * @param type         1老师，2校区老师，3校长，4校区
     * @return
     */
    public List<RenewClassRecord> getRenewRecord(String[] schoolIdList, String SubjectsId, Integer YearPart, Integer QuarterNum, String TeacherName, String StartDate, String EndDate, Integer type, List<Long> baseSchoolIdList) {

        QueryWrapper queryWrapper = new QueryWrapper();

        ////1老师，2校区老师，3校长，4校区
        if (schoolIdList.length > 0) {
            queryWrapper.in("school_id", schoolIdList);
        } else {
            if (type.equals(2)) {
                //校区老师状态，只能看自己所在校区的数据
                queryWrapper.in("school_id", baseSchoolIdList);
            }
        }

        queryWrapper.eq(StringUtils.isNotBlank(SubjectsId), "subjects_id", SubjectsId);
        queryWrapper.eq("year_part", YearPart);
        queryWrapper.eq("quarter_num", QuarterNum);
        queryWrapper.eq("deleted", 0);
        //queryWrapper.eq("status",1);

        Map<String, Integer> nextQuarter = ConfigData.getNextQuarter(YearPart, QuarterNum);

        List<RenewClassRecord> renewClassRecordList = null;
        List<String> groupBys;
        //1老师，2校区老师，3校长，4校区
        if (type.equals(1)) {
            queryWrapper.like(StringUtils.isNotBlank(TeacherName), "teacher_name", TeacherName);
            //where (`a`.`deleted` = 0) group by `a`.`teacher_id`,`c`.`subjects_id`,`c`.`quarter_num`
            groupBys = new ArrayList<>();
            groupBys.add("teacher_id");
            if (StringUtils.isNotBlank(SubjectsId)) {
                groupBys.add("subjects_id");
            }
            groupBys.add("quarter_num");
            queryWrapper.groupBy(groupBys);


            renewClassRecordList = renewClassMapper.getRenewRecordPerson(queryWrapper);
        } else if (type.equals(2)) {
            queryWrapper.like(StringUtils.isNotBlank(TeacherName), "teacher_name", TeacherName);
            //group by `a`.`school_id`,`a`.`teacher_id`,`c`.`subjects_id`,`c`.`quarter_num`
            groupBys = new ArrayList<>();
            groupBys.add("school_id");
            groupBys.add("teacher_id");
            if (StringUtils.isNotBlank(SubjectsId)) {
                groupBys.add("subjects_id");
            }
            groupBys.add("quarter_num");
            queryWrapper.groupBy(groupBys);

            renewClassRecordList = renewClassMapper.getRenewRecord(queryWrapper);
        } else if (type.equals(3)) {
            queryWrapper.like(StringUtils.isNotBlank(TeacherName), "teacher_name", TeacherName);
            queryWrapper.inSql("teacher_id", "select admin_id from role_admin where role_id = 1568160887369994242 ");

            groupBys = new ArrayList<>();
            groupBys.add("teacher_id");
            if (StringUtils.isNotBlank(SubjectsId)) {
                groupBys.add("subjects_id");
            }
            groupBys.add("quarter_num");
            queryWrapper.groupBy(groupBys);

            renewClassRecordList = renewClassMapper.getRenewRecordPerson(queryWrapper);
        } else if (type.equals(4)) {
            //where (`a`.`deleted` = 0) group by `a`.`school_id`,`c`.`subjects_id`,`c`.`quarter_num`
            groupBys = new ArrayList<>();
            groupBys.add("school_id");
            if (StringUtils.isNotBlank(SubjectsId)) {
                groupBys.add("subjects_id");
            }
            groupBys.add("quarter_num");
            queryWrapper.groupBy(groupBys);
            renewClassRecordList = renewClassMapper.getRenewRecordSchool(queryWrapper);
        }


        for (RenewClassRecord renewClassRecord : renewClassRecordList) {

            //@Param("schoolId") Long schoolId,@Param("subjectsId") Long subjectsId,@Param("renewTeacherId") Long renewTeacherId,@Param("yearPart") Integer yearPart,@Param("quarterNum") Integer quarterNum
            QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();

            //1老师，2校区老师，3校长，4校区
            if (type.equals(1)) {
                studentGradeQueryWrapper.inSql("grade_id", "select id from grade where teacher_id = " + renewClassRecord.getTeacherId() + "");
            } else if (type.equals(2)) {
                studentGradeQueryWrapper.eq("school_id", renewClassRecord.getSchoolId());
                studentGradeQueryWrapper.inSql("grade_id", "select id from grade where teacher_id = " + renewClassRecord.getTeacherId() + "");
            } else if (type.equals(3)) {
                studentGradeQueryWrapper.inSql("grade_id", "select id from grade where teacher_id = " + renewClassRecord.getTeacherId() + "");
            } else if (type.equals(4)) {
                studentGradeQueryWrapper.eq("school_id", renewClassRecord.getSchoolId());
            }

            studentGradeQueryWrapper.eq(StringUtils.isNotBlank(SubjectsId), "subjects_id", SubjectsId);
            studentGradeQueryWrapper.eq("year_part", YearPart);
            studentGradeQueryWrapper.eq("quarter_num", QuarterNum);
            studentGradeQueryWrapper.eq("deleted", 0);
            studentGradeQueryWrapper.ne("status", 2);
            studentGradeQueryWrapper.ne("status", 3);
            studentGradeQueryWrapper.ne("reading_status", 2);
            //studentGradeQueryWrapper.and(i->i.eq("status",1).or(j->j.ne("status",1).gt("use_course_count",0)));


            //studentGradeQueryWrapper.or(i->i.gt("use_course_count",0).ne("status",1).eq("deleted",0).eq("subjects_id",SubjectsId).eq("year_part",YearPart).eq("quarter_num",QuarterNum));

            Integer studentAllCount = renewClassMapper.getStudentAllCount(studentGradeQueryWrapper);
            renewClassRecord.setStudentAllCount(studentAllCount);


            //@Param("schoolId") Long schoolId, @Param("teacherId") Long teacherId, @Param("subjectsId") Long subjectsId, @Param("yearPart") Integer yearPart, @Param("quarterNum") Integer quarterNum, @Param("level") Integer level
            //,renewClassRecord.getTeacherId(),SubjectsId,nextQuarter.get("yearPart"),nextQuarter.get("num"),1
            //@Select("select  count(id) as count from renew_data where  level=#{level} and year_class_id <>9 and year_class_id is not null and type=1")

            //应续人数
            //1老师，2校区老师，3校长，4校区
            QueryWrapper<RenewData> renewDataQueryWrapper = new QueryWrapper<>();
            if (type.equals(1)) {
                renewDataQueryWrapper.eq("teacher_id", renewClassRecord.getTeacherId());
            } else if (type.equals(2)) {
                renewDataQueryWrapper.eq("teacher_id", renewClassRecord.getTeacherId());
                renewDataQueryWrapper.eq("school_id", renewClassRecord.getSchoolId());
            } else if (type.equals(3)) {
                //renewDataQueryWrapper.eq("school_id",renewClassRecord.getSchoolId());
                renewDataQueryWrapper.eq("teacher_id", renewClassRecord.getTeacherId());
            } else if (type.equals(4)) {
                renewDataQueryWrapper.eq("school_id", renewClassRecord.getSchoolId());
                renewDataQueryWrapper.inSql("teacher_id", "select teacher_id from grade where school_id=" + renewClassRecord.getSchoolId() + "");
            }

            renewDataQueryWrapper.eq(StringUtils.isNotBlank(SubjectsId), "subjects_id", SubjectsId);
            renewDataQueryWrapper.eq("year_part_renew", nextQuarter.get("yearPart"));
            renewDataQueryWrapper.eq("quarter_num_renew", nextQuarter.get("num"));
            renewDataQueryWrapper.eq("level", 1);
            renewDataQueryWrapper.isNotNull("year_class_id");
            renewDataQueryWrapper.eq("type", 1);


            //renewDataQueryWrapper.inSql("student_id","select student_id from student_grade as b left join grade as c on b.grade_id = c.id where c.teacher_id="+renewClassRecord.getTeacherId()+" and b.deleted=0 and b.status<>2 and b.reading_status=1 and b.subjects_id="+SubjectsId+" and b.year_part="+YearPart+" and b.quarter_num="+QuarterNum+"");
            //春续暑，暑续秋，9年级不算在续班率里
            if (QuarterNum.equals(2) || QuarterNum.equals(3)) {
                //小于 <
                renewDataQueryWrapper.lt("year_class_id", 9);
            } else {
                //小于等于 <=
                renewDataQueryWrapper.le("year_class_id", 9);
            }

            Integer shouldRenewCount = renewDataMapper.getShouldCount(renewDataQueryWrapper);
            renewClassRecord.setShouldRenewCount(shouldRenewCount);


            /**
             * 已续人数
             */

            QueryWrapper<RenewData> renewDataQueryWrapperAlready = new QueryWrapper<>();
            //1老师，2校区老师，3校长，4校区
            if (type.equals(1)) {
                renewDataQueryWrapperAlready.eq("teacher_id", renewClassRecord.getTeacherId());
            } else if (type.equals(2)) {
                renewDataQueryWrapperAlready.eq("teacher_id", renewClassRecord.getTeacherId());
                renewDataQueryWrapperAlready.eq("school_id", renewClassRecord.getSchoolId());
            } else if (type.equals(3)) {
                renewDataQueryWrapperAlready.eq("teacher_id", renewClassRecord.getTeacherId());
                //renewDataQueryWrapperAlready.eq("school_id",renewClassRecord.getSchoolId());
            } else if (type.equals(4)) {
                renewDataQueryWrapperAlready.eq("school_id", renewClassRecord.getSchoolId());
            }


            renewDataQueryWrapperAlready.eq(StringUtils.isNotBlank(SubjectsId), "subjects_id", SubjectsId);
            renewDataQueryWrapperAlready.eq("year_part_renew", nextQuarter.get("yearPart"));
            renewDataQueryWrapperAlready.eq("quarter_num_renew", nextQuarter.get("num"));
            renewDataQueryWrapperAlready.eq("level", 1);

            renewDataQueryWrapperAlready.isNotNull("year_class_id");
            renewDataQueryWrapperAlready.eq("type", 1);
            renewDataQueryWrapperAlready.eq("is_renew", 1);
            renewDataQueryWrapperAlready.eq("true_renew", 1);

            //renewDataQueryWrapperAlready.inSql("student_id","select student_id from student_grade as b left join grade as c on b.grade_id = c.id where c.teacher_id="+renewClassRecord.getTeacherId()+" and b.deleted=0 and b.status<>2 and b.reading_status=1 and b.subjects_id="+SubjectsId+" and b.year_part="+YearPart+" and b.quarter_num="+QuarterNum+"");
            if (QuarterNum.equals(2) || QuarterNum.equals(3)) {
                renewDataQueryWrapperAlready.lt("year_class_id", 9);
            } else {
                renewDataQueryWrapperAlready.le("year_class_id", 9);
            }

            if (StringUtils.isNotBlank(StartDate)) {
                renewDataQueryWrapperAlready.ge("renew_date", StartDate);
            }

            if (StringUtils.isNotBlank(EndDate)) {
                renewDataQueryWrapperAlready.le("renew_date", EndDate);
            }


            Integer alreadyRenewCount = renewDataMapper.getAlreadyShouldCount(renewDataQueryWrapperAlready);
            renewClassRecord.setAlreadyRenewCount(alreadyRenewCount);


            /**
             * //当天的续班人数，已续人数
             */
            LocalDate nowDate = LocalDate.now();

            renewDataQueryWrapperAlready = new QueryWrapper<>();
            //1老师，2校区老师，3校长，4校区
            if (type.equals(1)) {
                renewDataQueryWrapperAlready.eq("teacher_id", renewClassRecord.getTeacherId());
            } else if (type.equals(2)) {
                renewDataQueryWrapperAlready.eq("teacher_id", renewClassRecord.getTeacherId());
                renewDataQueryWrapperAlready.eq("school_id", renewClassRecord.getSchoolId());
            } else if (type.equals(3)) {
                //renewDataQueryWrapper.eq("school_id",renewClassRecord.getSchoolId());
                renewDataQueryWrapperAlready.eq("teacher_id", renewClassRecord.getTeacherId());
            } else if (type.equals(4)) {
                renewDataQueryWrapperAlready.eq("school_id", renewClassRecord.getSchoolId());
            }

            renewDataQueryWrapperAlready.eq(StringUtils.isNotBlank(SubjectsId), "subjects_id", SubjectsId);
            renewDataQueryWrapperAlready.eq("year_part_renew", nextQuarter.get("yearPart"));
            renewDataQueryWrapperAlready.eq("quarter_num_renew", nextQuarter.get("num"));
            renewDataQueryWrapperAlready.eq("level", 1);

            renewDataQueryWrapperAlready.isNotNull("year_class_id");
            renewDataQueryWrapperAlready.eq("type", 1);
            renewDataQueryWrapperAlready.eq("is_renew", 1);
            //renewDataQueryWrapperAlready.inSql("student_id","select student_id from student_grade as b left join grade as c on b.grade_id = c.id where c.teacher_id="+renewClassRecord.getTeacherId()+" and b.deleted=0 and b.status<>2 and b.reading_status=1 and b.subjects_id="+SubjectsId+" and b.year_part="+YearPart+" and b.quarter_num="+QuarterNum+"");
            if (QuarterNum.equals(2) || QuarterNum.equals(3)) {
                renewDataQueryWrapperAlready.lt("year_class_id", 9);
            } else {
                renewDataQueryWrapperAlready.le("year_class_id", 9);
            }
            renewDataQueryWrapperAlready.eq("renew_date", nowDate);

            Integer dateRenewCount = renewDataMapper.getAlreadyShouldCount(renewDataQueryWrapperAlready);
            renewClassRecord.setDateRenewCount(dateRenewCount);


            //流失率
            /*Integer runOffCount = renewClassMapper.getRunOffCount(renewClassRecord.getSchoolId(),Long.parseLong(SubjectsId),renewClassRecord.getTeacherId(),YearPart,QuarterNum);
            renewClassRecord.setRunOffCount(runOffCount);
            */
            if (shouldRenewCount > 0) {
                BigDecimal b1 = new BigDecimal(Double.toString(alreadyRenewCount));
                BigDecimal b2 = new BigDecimal(Double.toString(shouldRenewCount));
                BigDecimal b3 = b1.divide(b2, 2, BigDecimal.ROUND_HALF_UP);

                renewClassRecord.setRenewRate(b3.multiply(new BigDecimal(100)));
            }


            //float renewRate = renewClassRecord.getAlreadyRenewCount()/renewClassRecord.getShouldRenewCount();
        }
        return renewClassRecordList;
    }

    public List<RenewClassRecord> getRenewRecordForTeacher(String SubjectsId, Integer YearPart, Integer QuarterNum, String TeacherName, String StartDate, String EndDate) {

        QueryWrapper queryWrapper = new QueryWrapper();

        queryWrapper.eq(StringUtils.isNotBlank(SubjectsId), "subjects_id", SubjectsId);
        queryWrapper.eq("year_part", YearPart);
        queryWrapper.eq("quarter_num", QuarterNum);

        Map<String, Integer> nextQuarter = ConfigData.getNextQuarter(YearPart, QuarterNum);


        List<RenewClassRecord> renewClassRecordList = renewClassMapper.getRenewRecord(queryWrapper);
        for (RenewClassRecord renewClassRecord : renewClassRecordList) {

            QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
            studentGradeQueryWrapper.eq("school_id", renewClassRecord.getSchoolId());
            studentGradeQueryWrapper.eq("subjects_id", SubjectsId);
            studentGradeQueryWrapper.eq("teacher_id", renewClassRecord.getTeacherId());
            studentGradeQueryWrapper.eq("year_part", YearPart);
            studentGradeQueryWrapper.eq("quarter_num", QuarterNum);
            studentGradeQueryWrapper.eq("deleted", 0);
            studentGradeQueryWrapper.ne("status", 2);

            Integer studentAllCount = renewClassMapper.getStudentAllCount(studentGradeQueryWrapper);
            renewClassRecord.setStudentAllCount(studentAllCount);

            //应续人数
            QueryWrapper<RenewData> renewDataQueryWrapper = new QueryWrapper<>();
            renewDataQueryWrapper.eq("school_id", renewClassRecord.getSchoolId());
            renewDataQueryWrapper.eq("teacher_id", renewClassRecord.getSchoolId());
            renewDataQueryWrapper.eq(StringUtils.isNotBlank(SubjectsId), "subjects_id", SubjectsId);
            renewDataQueryWrapper.eq("year_part_renew", renewClassRecord.getSchoolId());
            renewDataQueryWrapper.eq("quarter_num_renew", renewClassRecord.getSchoolId());
            renewDataQueryWrapper.eq("level", renewClassRecord.getSchoolId());
            renewDataQueryWrapper.ne("year_class_id", 9);
            renewDataQueryWrapper.ne("year_class_id", null);
            renewDataQueryWrapper.ne("type", 1);

            Integer shouldRenewCount = renewDataMapper.getShouldCount(renewDataQueryWrapper);
            renewClassRecord.setShouldRenewCount(shouldRenewCount);


            /**
             * 已续人数
             */

            QueryWrapper<RenewData> renewDataQueryWrapperAlready = new QueryWrapper<>();
            renewDataQueryWrapper.eq("school_id", renewClassRecord.getSchoolId());
            renewDataQueryWrapper.eq("teacher_id", renewClassRecord.getTeacherId());
            renewDataQueryWrapper.eq(StringUtils.isNotBlank(SubjectsId), "subjects_id", SubjectsId);
            renewDataQueryWrapper.eq("year_part_renew", nextQuarter.get("yearPart"));
            renewDataQueryWrapper.eq("quarter_num_renew", nextQuarter.get("num"));
            renewDataQueryWrapper.eq("level", 1);
            renewDataQueryWrapper.ne("year_class_id", 9);
            renewDataQueryWrapper.ne("year_class_id", null);
            renewDataQueryWrapper.ne("type", 1);
            renewDataQueryWrapperAlready.ne("is_renew", 1);


            Integer alreadyRenewCount = renewDataMapper.getAlreadyShouldCount(renewDataQueryWrapperAlready);

            renewClassRecord.setAlreadyRenewCount(alreadyRenewCount);

            Integer runOffCount = renewClassMapper.getRunOffCount(renewClassRecord.getSchoolId(), Long.parseLong(SubjectsId), renewClassRecord.getTeacherId(), YearPart, QuarterNum);
            renewClassRecord.setRunOffCount(runOffCount);

            if (shouldRenewCount > 0) {
                BigDecimal b1 = new BigDecimal(Double.toString(alreadyRenewCount));
                BigDecimal b2 = new BigDecimal(Double.toString(shouldRenewCount));
                BigDecimal b3 = b1.divide(b2, 2, BigDecimal.ROUND_HALF_UP);

                renewClassRecord.setRenewRate(b3.multiply(new BigDecimal(100)));
            }
            //float renewRate = renewClassRecord.getAlreadyRenewCount()/renewClassRecord.getShouldRenewCount();
        }
        return renewClassRecordList;
    }

    /**
     * 赛道
     *
     * @param schoolIdList
     * @param SubjectsId
     * @param YearPart
     * @param QuarterNum
     * @param TeacherName
     * @param StartDate
     * @param EndDate
     * @param trackId
     * @return
     */
    public List<RenewClassRecord> getRenewRecordForTrack(String[] schoolIdList, String SubjectsId, Integer YearPart, Integer QuarterNum, String TeacherName, String StartDate, String EndDate, String trackId) {

        QueryWrapper queryWrapper = new QueryWrapper();
        if (schoolIdList.length > 0) {
            queryWrapper.in("school_id", schoolIdList);
        } else {
            //queryWrapper.eq("school_id",0);
        }

        Track track = trackMapper.selectById(trackId);
        if (track == null) {
            throw new CommonException(ResultCode.NOTDATA);
        }

        QueryWrapper<TrackDetail> trackDetailQueryWrapper = new QueryWrapper<>();
        trackDetailQueryWrapper.eq("track_id", track.getId());
        trackDetailQueryWrapper.eq("deleted", 0);
        trackDetailQueryWrapper.eq("classify", 1);//分类：1是续班赛道，2是招生赛道
        List<Long> sourceIdList = trackDetailMapper.getSourceIdList(trackDetailQueryWrapper);


        queryWrapper.eq(StringUtils.isNotBlank(SubjectsId), "subjects_id", SubjectsId);
        queryWrapper.eq("year_part", YearPart);
        queryWrapper.eq("quarter_num", QuarterNum);
        queryWrapper.eq("deleted", 0);
        //queryWrapper.eq("status",1);

        Map<String, Integer> nextQuarter = ConfigData.getNextQuarter(YearPart, QuarterNum);

        List<RenewClassRecord> renewClassRecordList = null;
        List<String> groupBys;
        if (track.getType().equals(1)) {
            queryWrapper.like(StringUtils.isNotBlank(TeacherName), "teacher_name", TeacherName);
            queryWrapper.in("teacher_id", sourceIdList);

            groupBys = new ArrayList<>();
            groupBys.add("teacher_id");
            if (StringUtils.isNotBlank(SubjectsId)) {
                groupBys.add("subjects_id");
            }
            groupBys.add("quarter_num");
            queryWrapper.groupBy(groupBys);

            renewClassRecordList = renewClassMapper.getRenewRecordPerson(queryWrapper);

        } else {
            queryWrapper.in("school_id", sourceIdList);

            groupBys = new ArrayList<>();
            groupBys.add("school_id");
            if (StringUtils.isNotBlank(SubjectsId)) {
                groupBys.add("subjects_id");
            }
            groupBys.add("quarter_num");
            queryWrapper.groupBy(groupBys);
            renewClassRecordList = renewClassMapper.getRenewRecordSchool(queryWrapper);
        }

        for (RenewClassRecord renewClassRecord : renewClassRecordList) {

            //@Param("schoolId") Long schoolId,@Param("subjectsId") Long subjectsId,@Param("renewTeacherId") Long renewTeacherId,@Param("yearPart") Integer yearPart,@Param("quarterNum") Integer quarterNum
            QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
            if (track.getType().equals(1)) {
                studentGradeQueryWrapper.inSql("grade_id", "select id from grade where teacher_id = " + renewClassRecord.getTeacherId() + "");
            } else {
                studentGradeQueryWrapper.eq("school_id", renewClassRecord.getSchoolId());
            }

            studentGradeQueryWrapper.eq(StringUtils.isNotBlank(SubjectsId), "subjects_id", SubjectsId);
            studentGradeQueryWrapper.eq("year_part", YearPart);
            studentGradeQueryWrapper.eq("quarter_num", QuarterNum);
            studentGradeQueryWrapper.eq("deleted", 0);
            studentGradeQueryWrapper.ne("status", 2);
            studentGradeQueryWrapper.ne("status", 3);
            studentGradeQueryWrapper.ne("reading_status", 2);
            //studentGradeQueryWrapper.and(i->i.eq("status",1).or(j->j.ne("status",1).gt("use_course_count",0)));


            //studentGradeQueryWrapper.or(i->i.gt("use_course_count",0).ne("status",1).eq("deleted",0).eq("subjects_id",SubjectsId).eq("year_part",YearPart).eq("quarter_num",QuarterNum));

            Integer studentAllCount = renewClassMapper.getStudentAllCount(studentGradeQueryWrapper);
            renewClassRecord.setStudentAllCount(studentAllCount);


            //@Param("schoolId") Long schoolId, @Param("teacherId") Long teacherId, @Param("subjectsId") Long subjectsId, @Param("yearPart") Integer yearPart, @Param("quarterNum") Integer quarterNum, @Param("level") Integer level
            //,renewClassRecord.getTeacherId(),SubjectsId,nextQuarter.get("yearPart"),nextQuarter.get("num"),1
            //@Select("select  count(id) as count from renew_data where  level=#{level} and year_class_id <>9 and year_class_id is not null and type=1")

            //应续人数
            //1老师，2校区老师，3校长，4校区
            QueryWrapper<RenewData> renewDataQueryWrapper = new QueryWrapper<>();
            if (track.getType().equals(1)) {
                renewDataQueryWrapper.eq("teacher_id", renewClassRecord.getTeacherId());
            } else {
                renewDataQueryWrapper.eq("school_id", renewClassRecord.getSchoolId());
                renewDataQueryWrapper.inSql("teacher_id", "select teacher_id from grade where school_id=" + renewClassRecord.getSchoolId() + "");
            }

            renewDataQueryWrapper.eq(StringUtils.isNotBlank(SubjectsId), "subjects_id", SubjectsId);
            renewDataQueryWrapper.eq("year_part_renew", nextQuarter.get("yearPart"));
            renewDataQueryWrapper.eq("quarter_num_renew", nextQuarter.get("num"));
            renewDataQueryWrapper.eq("level", 1);
            renewDataQueryWrapper.isNotNull("year_class_id");
            renewDataQueryWrapper.eq("type", 1);


            //renewDataQueryWrapper.inSql("student_id","select student_id from student_grade as b left join grade as c on b.grade_id = c.id where c.teacher_id="+renewClassRecord.getTeacherId()+" and b.deleted=0 and b.status<>2 and b.reading_status=1 and b.subjects_id="+SubjectsId+" and b.year_part="+YearPart+" and b.quarter_num="+QuarterNum+"");
            //春续暑，暑续秋，9年级不算在续班率里
            if (QuarterNum.equals(2) || QuarterNum.equals(3)) {
                //小于 <
                renewDataQueryWrapper.lt("year_class_id", 9);
            } else {
                //小于等于 <=
                renewDataQueryWrapper.le("year_class_id", 9);
            }

            Integer shouldRenewCount = renewDataMapper.getShouldCount(renewDataQueryWrapper);
            renewClassRecord.setShouldRenewCount(shouldRenewCount);


            /**
             * 已续人数
             */

            QueryWrapper<RenewData> renewDataQueryWrapperAlready = new QueryWrapper<>();

            if (track.getType().equals(1)) {
                renewDataQueryWrapperAlready.eq("teacher_id", renewClassRecord.getTeacherId());
            } else {
                renewDataQueryWrapperAlready.eq("school_id", renewClassRecord.getSchoolId());
                //renewDataQueryWrapper.inSql("teacher_id","select teacher_id from grade where school_id="+renewClassRecord.getSchoolId()+"");
            }

            renewDataQueryWrapperAlready.eq(StringUtils.isNotBlank(SubjectsId), "subjects_id", SubjectsId);
            renewDataQueryWrapperAlready.eq("year_part_renew", nextQuarter.get("yearPart"));
            renewDataQueryWrapperAlready.eq("quarter_num_renew", nextQuarter.get("num"));
            renewDataQueryWrapperAlready.eq("level", 1);

            renewDataQueryWrapperAlready.isNotNull("year_class_id");
            renewDataQueryWrapperAlready.eq("type", 1);
            renewDataQueryWrapperAlready.eq("is_renew", 1);
            //renewDataQueryWrapperAlready.inSql("student_id","select student_id from student_grade as b left join grade as c on b.grade_id = c.id where c.teacher_id="+renewClassRecord.getTeacherId()+" and b.deleted=0 and b.status<>2 and b.reading_status=1 and b.subjects_id="+SubjectsId+" and b.year_part="+YearPart+" and b.quarter_num="+QuarterNum+"");
            if (QuarterNum.equals(2) || QuarterNum.equals(3)) {
                renewDataQueryWrapperAlready.lt("year_class_id", 9);
            } else {
                renewDataQueryWrapperAlready.le("year_class_id", 9);
            }

            if (StringUtils.isNotBlank(StartDate)) {
                renewDataQueryWrapperAlready.ge("renew_date", StartDate);
            }

            if (StringUtils.isNotBlank(EndDate)) {
                renewDataQueryWrapperAlready.le("renew_date", EndDate);
            }


            Integer alreadyRenewCount = renewDataMapper.getAlreadyShouldCount(renewDataQueryWrapperAlready);
            renewClassRecord.setAlreadyRenewCount(alreadyRenewCount);


            /**
             * //当天的续班人数，已续人数
             */

            LocalDate nowDate = LocalDate.now();

            renewDataQueryWrapperAlready = new QueryWrapper<>();
            if (track.getType().equals(1)) {
                renewDataQueryWrapperAlready.eq("teacher_id", renewClassRecord.getTeacherId());
            } else {
                renewDataQueryWrapperAlready.eq("school_id", renewClassRecord.getSchoolId());
                //renewDataQueryWrapper.inSql("teacher_id","select teacher_id from grade where school_id="+renewClassRecord.getSchoolId()+"");
            }

            renewDataQueryWrapperAlready.eq(StringUtils.isNotBlank(SubjectsId), "subjects_id", SubjectsId);
            renewDataQueryWrapperAlready.eq("year_part_renew", nextQuarter.get("yearPart"));
            renewDataQueryWrapperAlready.eq("quarter_num_renew", nextQuarter.get("num"));
            renewDataQueryWrapperAlready.eq("level", 1);

            renewDataQueryWrapperAlready.isNotNull("year_class_id");
            renewDataQueryWrapperAlready.eq("type", 1);
            renewDataQueryWrapperAlready.eq("is_renew", 1);
            //renewDataQueryWrapperAlready.inSql("student_id","select student_id from student_grade as b left join grade as c on b.grade_id = c.id where c.teacher_id="+renewClassRecord.getTeacherId()+" and b.deleted=0 and b.status<>2 and b.reading_status=1 and b.subjects_id="+SubjectsId+" and b.year_part="+YearPart+" and b.quarter_num="+QuarterNum+"");
            if (QuarterNum.equals(2) || QuarterNum.equals(3)) {
                renewDataQueryWrapperAlready.lt("year_class_id", 9);
            } else {
                renewDataQueryWrapperAlready.le("year_class_id", 9);
            }
            renewDataQueryWrapperAlready.eq("renew_date", nowDate);

            Integer dateRenewCount = renewDataMapper.getAlreadyShouldCount(renewDataQueryWrapperAlready);
            renewClassRecord.setDateRenewCount(dateRenewCount);


            //流失率
            /*Integer runOffCount = renewClassMapper.getRunOffCount(renewClassRecord.getSchoolId(),Long.parseLong(SubjectsId),renewClassRecord.getTeacherId(),YearPart,QuarterNum);
            renewClassRecord.setRunOffCount(runOffCount);
*/
            if (shouldRenewCount > 0) {
                BigDecimal b1 = new BigDecimal(Double.toString(alreadyRenewCount));
                BigDecimal b2 = new BigDecimal(Double.toString(shouldRenewCount));
                BigDecimal b3 = b1.divide(b2, 2, BigDecimal.ROUND_HALF_UP);

                renewClassRecord.setRenewRate(b3.multiply(new BigDecimal(100)));
            }
            //float renewRate = renewClassRecord.getAlreadyRenewCount()/renewClassRecord.getShouldRenewCount();
        }
        return renewClassRecordList;
    }

    @Override
    public List<RenewClassRecord> getPayFee(String schoolId, Integer yearPart, Integer quarterNum, String subjectsId, Integer type, String startDate, String endDate, String trackId, Integer lessonType, String yearClassId, String classTypeId, Integer periodsNum, String name, AuthAdminContent authAdminContent, LeadDataRs leadDataRs, Integer versionNum, Integer paymentStaff, Integer paymentStaffType, Integer isDetails, String teacherId, Long adminId, Integer isCourseScheduling, String timeStart, String timeEnd) throws ParseException {
        Quarter quarterNow = iQuarterService.getNowQuarter();

        //期数，1期为45，2期为90
        Integer feeCourseNum = this.getCourseNumForPeriods(periodsNum);

        if (yearPart == null) {
            yearPart = quarterNow.getYearPart();
        }
        if (quarterNum == null) {
            quarterNum = quarterNow.getNum();
        }
        RenewHistoryData renewHistoryData = this.getHistoryData(yearPart, quarterNum, endDate, quarterNow);
        //是否查看历史的，1是，0否，查看历史的要使用(整个学期)历史表
        Integer isHistory = renewHistoryData.getIsHistory();
        Integer targetType = renewHistoryData.getTargetType();//0校长指标，1老师指标
        boolean dateHistory = renewHistoryData.isDateHistory();//按天看的历史数据

        Integer payYearPart = yearPart;
        Integer payQuarterNum = quarterNum;

        Integer searchYearAndQuarter = Integer.parseInt(yearPart + "" + quarterNum);
        Integer nextYearAndQuarter = 0;
        if (isHistory.equals(1) && targetType.equals(1)) {
            Integer quarterId = iQuarterService.getIdForYearPartAndNum(yearPart, quarterNum);
            Quarter nextQuater = iQuarterService.getQuarterMaxForId(quarterId + 1);//获取当前学期的下个学期后的学期
            if (nextQuater != null) {
                nextYearAndQuarter = Integer.parseInt(nextQuater.getYearPart() + "" + nextQuater.getNum());
            }
            payYearPart = quarterNow.getYearPart();
            payQuarterNum = quarterNow.getNum();
        }

        List<RenewClassRecord> renewClassRecordList = new ArrayList<>();

        if (versionNum.equals(1)) {
            if (!dateHistory) {
                //orderDetailMapper.createStudentResidueCourseTempTb();
                renewClassRecordList = orderDetailMapper.getPayFee(schoolId, yearPart, quarterNum, subjectsId, type, startDate, endDate, trackId, isHistory, lessonType, searchYearAndQuarter, nextYearAndQuarter, payYearPart, payQuarterNum, yearClassId, classTypeId, feeCourseNum, periodsNum, name, authAdminContent, leadDataRs, isCourseScheduling, timeStart, timeEnd);
            } else {
                orderDetailMapper.createStudentResidueCourseTempTb();
                orderDetailMapper.addDataToResidueCourseTempTb(schoolId, yearPart, quarterNum, subjectsId, type, startDate, endDate, trackId, lessonType, yearClassId, classTypeId, feeCourseNum, periodsNum, name, authAdminContent, leadDataRs);
                renewClassRecordList = orderDetailMapper.getPayFeeByHistory(schoolId, yearPart, quarterNum, subjectsId, type, startDate, endDate, trackId, lessonType, yearClassId, classTypeId, feeCourseNum, periodsNum, name, authAdminContent, leadDataRs);
            }

            if (type == 6) {

                List<RenewClassRecord> collectList = new ArrayList<>();

                QueryWrapper queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("year_part", yearPart);
                queryWrapper.eq("quarter_num", quarterNum);
                queryWrapper.eq("pid", 0);
                List<SchoolQuarter> schoolQuarterList = iSchoolQuarterService.list(queryWrapper);

                for (SchoolQuarter schoolQuarter : schoolQuarterList) {
                    RenewClassRecord practicePlanStaff = new RenewClassRecord();
                    practicePlanStaff.setSchoolId(schoolQuarter.getSchoolId());
                    practicePlanStaff.setSchoolName(schoolQuarter.getSchoolName());
                    practicePlanStaff.setSchoolPid(schoolQuarter.getPid());
                    practicePlanStaff.setStudentAllCount(0);
                    practicePlanStaff.setBigFifteen(0);
                    practicePlanStaff.setLittleFifteen(0);
                    practicePlanStaff.setPayNum(0);

                    collectList.add(practicePlanStaff);
                }

                for (RenewClassRecord practicePlanStaff : collectList) {
                    List<RenewClassRecord> childRates = new ArrayList<>();
                    for (RenewClassRecord planStaff : renewClassRecordList) {
                        if (practicePlanStaff.getSchoolId().equals(planStaff.getSchoolId()) || practicePlanStaff.getSchoolId().equals(planStaff.getSchoolPid())) {
                            childRates.add(planStaff);
                            if (planStaff.getStudentAllCount() != null) {
                                practicePlanStaff.setStudentAllCount(practicePlanStaff.getStudentAllCount() + planStaff.getStudentAllCount());
                            }
                            if (planStaff.getBigFifteen() != null) {
                                practicePlanStaff.setBigFifteen(practicePlanStaff.getBigFifteen() + planStaff.getBigFifteen());
                            }
                            if (planStaff.getLittleFifteen() != null) {
                                practicePlanStaff.setLittleFifteen(practicePlanStaff.getLittleFifteen() + planStaff.getLittleFifteen());
                            }
                            if (planStaff.getPayNum() != null) {
                                practicePlanStaff.setPayNum(practicePlanStaff.getPayNum() + planStaff.getPayNum());
                            }
                        }
                    }
                    practicePlanStaff.setChildren(childRates);
                }

                renewClassRecordList = collectList;

            }

        } else if (versionNum.equals(2)) {

            String departmentId = "0";
            Integer dutyType = 0;

            if (paymentStaff.equals(1)) {
                // 教学主管
                departmentId = "23";
                dutyType = 1;
            } else if (paymentStaff.equals(2)) {
                // 市场
                departmentId = "27";
                dutyType = 1;
            } else if (paymentStaff.equals(3)) {
                // 年级负责人
                departmentId = "23";
                dutyType = 2;
            } else if (paymentStaff.equals(6)) {
                // 小校区主管
                departmentId = "24,25";
                dutyType = 1;
            }

            if (!dateHistory) {
                renewClassRecordList = orderDetailMapper.getPayFeeV2(schoolId, yearPart, quarterNum, subjectsId, type, startDate, endDate, trackId, isHistory, lessonType, searchYearAndQuarter, nextYearAndQuarter, payYearPart, payQuarterNum, yearClassId, classTypeId, feeCourseNum, periodsNum, name, authAdminContent, leadDataRs, paymentStaff, paymentStaffType, departmentId, dutyType, isDetails, teacherId, adminId);
            } else {
                orderDetailMapper.createStudentResidueCourseTempTb();
                orderDetailMapper.addDataToResidueCourseTempTbV2(schoolId, yearPart, quarterNum, subjectsId, type, startDate, endDate, trackId, lessonType, yearClassId, classTypeId, feeCourseNum, periodsNum, name, authAdminContent, leadDataRs, paymentStaff, paymentStaffType);
                renewClassRecordList = orderDetailMapper.getPayFeeByHistoryV2(schoolId, yearPart, quarterNum, subjectsId, type, startDate, endDate, trackId, lessonType, yearClassId, classTypeId, feeCourseNum, periodsNum, name, authAdminContent, leadDataRs, paymentStaff, paymentStaffType, departmentId, dutyType, isDetails, teacherId);
            }

            if (paymentStaffType != 4) {
                if (renewClassRecordList.size() > 0) {
                    Map<Object, RenewClassRecord> mergedMap = new HashMap<>();
                    for (RenewClassRecord record : renewClassRecordList) {

                        RenewClassRecord mergedRecord = mergedMap.get(record.getTeacherId());
                        if (mergedRecord == null) {
                            mergedRecord = new RenewClassRecord();
                            mergedRecord.setTeacherId(record.getTeacherId());
                            mergedRecord.setTeacherName(record.getTeacherName());
                            mergedRecord.setSchoolPid(record.getSchoolPid());
                            mergedRecord.setStudentAllCount(0);
                            mergedRecord.setBigFifteen(0);
                            mergedRecord.setLittleFifteen(0);
                            mergedRecord.setPayNum(0);
                            mergedRecord.setChildren(new ArrayList<>());
                            mergedMap.put(record.getTeacherId(), mergedRecord);
                        }

                        mergedRecord.getChildren().add(record);

                        if (record.getStudentAllCount() != null) {
                            mergedRecord.setStudentAllCount(mergedRecord.getStudentAllCount() + record.getStudentAllCount());
                        }
                        if (record.getBigFifteen() != null) {
                            mergedRecord.setBigFifteen(mergedRecord.getBigFifteen() + record.getBigFifteen());
                        }
                        if (record.getLittleFifteen() != null) {
                            mergedRecord.setLittleFifteen(mergedRecord.getLittleFifteen() + record.getLittleFifteen());
                        }
                        if (record.getPayNum() != null) {
                            mergedRecord.setPayNum(mergedRecord.getPayNum() + record.getPayNum());
                        }
                    }

                    renewClassRecordList.clear();
                    renewClassRecordList.addAll(mergedMap.values());
                }
            }
        }

        return renewClassRecordList;
    }

    @Override
    public List<RenewClassRecord> getPayFeeMarket(String schoolId, Integer yearPart, Integer quarterNum, String
            subjectsId, Integer type, String startDate, String endDate, String trackId, Integer lessonType, String
                                                          yearClassId, String classTypeId, Integer periodsNum, String marketTeacherId, Integer trackType, Integer
                                                          classify, String teamId, AuthAdminContent authAdminContent, LeadDataRs leadDataRs) throws ParseException {

        LocalDate dateNow = LocalDate.now();
        //期数，1期为45，2期为90
        Integer feeCourseNum = this.getCourseNumForPeriods(periodsNum);
        Quarter quarterNow = iQuarterService.getNowQuarter();
        if (yearPart == null) {
            yearPart = quarterNow.getYearPart();
        }
        if (quarterNum == null) {
            quarterNum = quarterNow.getNum();
        }

        RenewHistoryData renewHistoryData = this.getHistoryData(yearPart, quarterNum, endDate, quarterNow);
        //是否查看历史的，1是，0否，查看历史的要使用(整个学期)历史表
        Integer isHistory = renewHistoryData.getIsHistory();
        Integer targetType = renewHistoryData.getTargetType();//0校长指标，1老师指标
        boolean dateHistory = renewHistoryData.isDateHistory();//按天看的历史数据

        Integer payYearPart = yearPart;//查询已缴的年份
        Integer payQuarterNum = quarterNum;//查询已缴的学期

        Integer searchYearAndQuarter = Integer.parseInt(yearPart + "" + quarterNum);
        Integer nextYearAndQuarter = 0;
        //老师指标，加上下一个学期的剩余课时
        if (isHistory.equals(1) && targetType.equals(1)) {
            Integer quarterId = iQuarterService.getIdForYearPartAndNum(yearPart, quarterNum);
            Quarter nextQuater = iQuarterService.getQuarterMaxForId(quarterId + 1);//获取当前学期的下个学期后的学期
            if (nextQuater != null) {
                nextYearAndQuarter = Integer.parseInt(nextQuater.getYearPart() + "" + nextQuater.getNum());
            }
            payYearPart = quarterNow.getYearPart();
            payQuarterNum = quarterNow.getNum();
        }

        if (StringUtils.isNotBlank(teamId)) {
            String teamIdItem = trackMarketMapper.getTrackMarketChIdAll(Long.parseLong(teamId));
            if (StringUtils.isNotBlank(teamIdItem)) {
                teamId = teamIdItem;
            }
        }

        List<RenewClassRecord> renewClassRecordList;
        if (!dateHistory) {
            renewClassRecordList = orderDetailMapper.getPayFeeMarket(schoolId, yearPart, quarterNum, subjectsId, type, startDate, endDate, trackId, isHistory, lessonType, searchYearAndQuarter, nextYearAndQuarter, payYearPart, payQuarterNum, yearClassId, classTypeId, feeCourseNum, marketTeacherId, trackType, classify, teamId, periodsNum, authAdminContent, leadDataRs);
        } else {
            renewClassRecordList = orderDetailMapper.getPayFeeMarketHistory(schoolId, yearPart, quarterNum, subjectsId, type, startDate, endDate, trackId, isHistory, lessonType, searchYearAndQuarter, nextYearAndQuarter, payYearPart, payQuarterNum, yearClassId, classTypeId, feeCourseNum, marketTeacherId, trackType, classify, teamId, periodsNum, authAdminContent, leadDataRs);
        }
        return renewClassRecordList;
    }

    @Override
    public List<RenewClassRecord> getPayFeeMarketForTeam(String schoolId, Integer yearPart, Integer
            quarterNum, String subjectsId, Integer type, String startDate, String endDate, String trackId, Integer
                                                                 lessonType, String yearClassId, String classTypeId, Integer periodsNum, String marketTeacherId, Integer
                                                                 trackType, Integer classify, String teamId, AuthAdminContent authAdminContent, LeadDataRs leadDataRs) throws
            ParseException {

        List<RenewClassRecord> renewClassRecordList = this.getPayFeeMarket(schoolId, yearPart, quarterNum, subjectsId, type, startDate, endDate, trackId, lessonType, yearClassId, classTypeId, periodsNum, marketTeacherId, trackType, classify, teamId, authAdminContent, leadDataRs);

        List<RenewClassRecord> classRecordList = new ArrayList<>();
        List<Long> marketIds = new ArrayList<>();
        List<Long> pidList = new ArrayList<>();
        for (RenewClassRecord renewClassRecord : renewClassRecordList) {
            marketIds.add(renewClassRecord.getTeamPid());

            TrackMarket trackMarket = iTrackMarketService.getById(renewClassRecord.getTeamPid());
            if (trackMarket == null) {
                continue;
            }
            if (!pidList.contains(renewClassRecord.getTeamPid())) {
                RenewClassRecord renewClassRecordInfo = new RenewClassRecord();
                renewClassRecordInfo.setTeacherName(trackMarket.getTeamName());
                renewClassRecordInfo.setTeamId(trackMarket.getId());
                renewClassRecordInfo.setTeamPid(trackMarket.getPid());
                renewClassRecordInfo.setYearPart(renewClassRecord.getYearPart());
                renewClassRecordInfo.setQuarterNum(renewClassRecord.getQuarterNum());
                renewClassRecordInfo.setLittleFifteen(0);
                renewClassRecordInfo.setBigFifteen(0);
                renewClassRecordInfo.setStudentAllCount(0);
                renewClassRecordInfo.setPayNum(0);
                classRecordList.add(renewClassRecordInfo);
            }
            pidList.add(renewClassRecord.getTeamPid());
        }
        //已经存在就不添加
        for (RenewClassRecord renewClassRecord : classRecordList) {
            if (marketIds.contains(renewClassRecord.getTeamId())) {
                renewClassRecordList.add(renewClassRecord);
            }
        }

        //获取父节点
        List<RenewClassRecord> collect = renewClassRecordList.stream().filter(m -> m.getTeamPid() == 0).map(
                (m) -> {
                    m.setChildren(getChildrens(m, renewClassRecordList));
                    return m;
                }
        ).collect(Collectors.toList());

        for (RenewClassRecord renewClassRecord : collect) {
            Integer littleFifteen = renewClassRecord.getLittleFifteen();
            Integer bigFifteen = renewClassRecord.getBigFifteen();
            Integer studentAllCount = renewClassRecord.getStudentAllCount();
            Integer payNum = renewClassRecord.getPayNum();
            if (renewClassRecord.getChildren().size() > 0) {
                List<RenewClassRecord> renewClassRecordList1 = renewClassRecord.getChildren();
                for (RenewClassRecord renewClassRecord1 : renewClassRecordList1) {
                    littleFifteen += renewClassRecord1.getLittleFifteen();
                    bigFifteen += renewClassRecord1.getBigFifteen();
                    studentAllCount += renewClassRecord1.getStudentAllCount();
                    payNum += renewClassRecord1.getPayNum();
                }
            }
            renewClassRecord.setLittleFifteen(littleFifteen);
            renewClassRecord.setBigFifteen(bigFifteen);
            renewClassRecord.setStudentAllCount(studentAllCount);
            renewClassRecord.setPayNum(payNum);
        }
        return collect;
    }

    private List<RenewClassRecord> getChildrens(RenewClassRecord root, List<RenewClassRecord> all) {
        List<RenewClassRecord> children = all.stream().filter(m ->
                Objects.equals(m.getTeamPid(), root.getTeamId())
        ).map(
                (m) -> {
                    m.setChildren(getChildrens(m, all));
                    return m;
                }
        ).collect(Collectors.toList());
        return children;
    }


    @Override
    public IPage<StudentRatePay> getPayDetailList(IPage<StudentRatePay> iPage,
                                                  Integer yearPart,
                                                  Integer quarterNum,
                                                  String schoolId,
                                                  String teacherId,
                                                  String gradeId,
                                                  String subjectsId,
                                                  Integer type,
                                                  String startDate,
                                                  String endDate,
                                                  String trackId,
                                                  String detailType,
                                                  String lessonType,
                                                  String yearClassId,
                                                  String classTypeId,
                                                  Integer periodsNum,
                                                  Integer isNextDateNum,
                                                  AuthAdminContent authAdminContent,
                                                  LeadDataRs leadDataRs,
                                                  Integer paymentStaff,
                                                  Integer paymentStaffType,
                                                  Integer versionNum,
                                                  String paymentStaffId,
                                                  Integer isCourseScheduling,
                                                  String timeStart,
                                                  String timeEnd) {

        //期数，1期为45，2期为90
        Integer feeCourseNum = this.getCourseNumForPeriods(periodsNum);

        Quarter quarterNow = iQuarterService.getNowQuarter();
        if (yearPart == null) {
            yearPart = quarterNow.getYearPart();
        }
        if (quarterNum == null) {
            quarterNum = quarterNow.getNum();
        }

        RenewHistoryData renewHistoryData = this.getHistoryData(yearPart, quarterNum, endDate, quarterNow);
        //是否查看历史的，1是，0否，查看历史的要使用(整个学期)历史表
        Integer isHistory = renewHistoryData.getIsHistory();
        Integer targetType = renewHistoryData.getTargetType();//0校长指标，1老师指标
        boolean dateHistory = renewHistoryData.isDateHistory();//按天看的历史数据

        Integer payYearPart = yearPart;
        Integer payQuarterNum = quarterNum;

        Integer searchYearAndQuarter = Integer.parseInt(yearPart + "" + quarterNum);
        Integer nextYearAndQuarter = 0;
        if (isHistory.equals(1) && targetType.equals(1)) {
            Integer quarterId = iQuarterService.getIdForYearPartAndNum(yearPart, quarterNum);
            Quarter nextQuater = iQuarterService.getQuarterMaxForId(quarterId + 1);//获取当前学期的两个学期后的学期
            if (nextQuater != null) {
                nextYearAndQuarter = Integer.parseInt(nextQuater.getYearPart() + "" + nextQuater.getNum());
            }
            payYearPart = quarterNow.getYearPart();
            payQuarterNum = quarterNow.getNum();
        }

        IPage<StudentRatePay> studentRatePayList = null;

        if (versionNum.equals(1)) {
            if (!dateHistory) {
                if (detailType.equals("3")) {
                    if (isNextDateNum == 1) {
                        studentRatePayList = orderDetailMapper.getRatePayFeeDetailV02(iPage, yearPart, quarterNum, schoolId, teacherId, gradeId, subjectsId, type, startDate, endDate, trackId, detailType, isHistory, lessonType, searchYearAndQuarter, nextYearAndQuarter, payYearPart, payQuarterNum, yearClassId, classTypeId, periodsNum, authAdminContent, leadDataRs, isCourseScheduling, timeStart, timeEnd);
                    } else {
                        studentRatePayList = orderDetailMapper.getRatePayFeeDetail(iPage, yearPart, quarterNum, schoolId, teacherId, gradeId, subjectsId, type, startDate, endDate, trackId, detailType, isHistory, lessonType, searchYearAndQuarter, nextYearAndQuarter, payYearPart, payQuarterNum, yearClassId, classTypeId, periodsNum, authAdminContent, leadDataRs, isCourseScheduling, timeStart, timeEnd);
                    }
                } else {
                    studentRatePayList = orderDetailMapper.getPayFeeDetail(iPage, yearPart, quarterNum, schoolId, teacherId, gradeId, subjectsId, type, startDate, endDate, trackId, detailType, isHistory, lessonType, searchYearAndQuarter, nextYearAndQuarter, yearClassId, classTypeId, feeCourseNum, authAdminContent, leadDataRs, isCourseScheduling, timeStart, timeEnd);
                }
            } else {
                if (detailType.equals("3")) {
                    if (isNextDateNum == 1) {
                        studentRatePayList = orderDetailMapper.getRatePayFeeDetailV02(iPage, yearPart, quarterNum, schoolId, teacherId, gradeId, subjectsId, type, startDate, endDate, trackId, detailType, isHistory, lessonType, searchYearAndQuarter, nextYearAndQuarter, payYearPart, payQuarterNum, yearClassId, classTypeId, periodsNum, authAdminContent, leadDataRs, isCourseScheduling, timeStart, timeEnd);
                    } else {
                        studentRatePayList = orderDetailMapper.getRatePayFeeDetail(iPage, yearPart, quarterNum, schoolId, teacherId, gradeId, subjectsId, type, startDate, endDate, trackId, detailType, isHistory, lessonType, searchYearAndQuarter, nextYearAndQuarter, payYearPart, payQuarterNum, yearClassId, classTypeId, periodsNum, authAdminContent, leadDataRs, isCourseScheduling, timeStart, timeEnd);
                    }
                } else {
                    studentRatePayList = orderDetailMapper.getPayFeeDetailHistory(iPage, yearPart, quarterNum, schoolId, teacherId, gradeId, subjectsId, type, startDate, endDate, trackId, detailType, lessonType, yearClassId, classTypeId, feeCourseNum, authAdminContent, leadDataRs);
                }
            }
        } else if (versionNum.equals(2)) {
            String departmentId = "0";
            Integer dutyType = 0;

            if (paymentStaff.equals(1)) {
                // 教学主管
                departmentId = "23";
                dutyType = 1;
            } else if (paymentStaff.equals(2)) {
                // 市场
                departmentId = "27";
                dutyType = 1;
            } else if (paymentStaff.equals(3)) {
                // 年级负责人
                departmentId = "23";
                dutyType = 2;
            } else if (paymentStaff.equals(6)) {
                // 小校区主管
                departmentId = "24,25";
                dutyType = 1;
            }

            if (!dateHistory) {
                if (detailType.equals("3")) {
                    if (isNextDateNum == 1) {
                        studentRatePayList = orderDetailMapper.getRatePayFeeDetailV03(iPage, yearPart, quarterNum, schoolId, teacherId, gradeId, subjectsId, type, startDate, endDate, trackId, detailType, isHistory, lessonType, searchYearAndQuarter, nextYearAndQuarter, payYearPart, payQuarterNum, yearClassId, classTypeId, periodsNum, authAdminContent, leadDataRs, paymentStaff, paymentStaffType, departmentId, dutyType, paymentStaffId);
                    } else {
                        studentRatePayList = orderDetailMapper.getRatePayFeeDetailV2(iPage, yearPart, quarterNum, schoolId, teacherId, gradeId, subjectsId, type, startDate, endDate, trackId, detailType, isHistory, lessonType, searchYearAndQuarter, nextYearAndQuarter, payYearPart, payQuarterNum, yearClassId, classTypeId, periodsNum, authAdminContent, leadDataRs, paymentStaff, paymentStaffType, departmentId, dutyType, paymentStaffId);
                    }
                } else {
                    studentRatePayList = orderDetailMapper.getPayFeeDetailV2(iPage, yearPart, quarterNum, schoolId, teacherId, gradeId, subjectsId, type, startDate, endDate, trackId, detailType, isHistory, lessonType, searchYearAndQuarter, nextYearAndQuarter, yearClassId, classTypeId, feeCourseNum, authAdminContent, leadDataRs, paymentStaff, paymentStaffType, departmentId, dutyType, paymentStaffId);
                }
            } else {
                if (detailType.equals("3")) {
                    if (isNextDateNum == 1) {
                        studentRatePayList = orderDetailMapper.getRatePayFeeDetailV03(iPage, yearPart, quarterNum, schoolId, teacherId, gradeId, subjectsId, type, startDate, endDate, trackId, detailType, isHistory, lessonType, searchYearAndQuarter, nextYearAndQuarter, payYearPart, payQuarterNum, yearClassId, classTypeId, periodsNum, authAdminContent, leadDataRs, paymentStaff, paymentStaffType, departmentId, dutyType, paymentStaffId);
                    } else {
                        studentRatePayList = orderDetailMapper.getRatePayFeeDetailV2(iPage, yearPart, quarterNum, schoolId, teacherId, gradeId, subjectsId, type, startDate, endDate, trackId, detailType, isHistory, lessonType, searchYearAndQuarter, nextYearAndQuarter, payYearPart, payQuarterNum, yearClassId, classTypeId, periodsNum, authAdminContent, leadDataRs, paymentStaff, paymentStaffType, departmentId, dutyType, paymentStaffId);
                    }
                } else {
                    studentRatePayList = orderDetailMapper.getPayFeeDetailHistoryV2(iPage, yearPart, quarterNum, schoolId, teacherId, gradeId, subjectsId, type, startDate, endDate, trackId, detailType, lessonType, yearClassId, classTypeId, feeCourseNum, authAdminContent, leadDataRs, paymentStaff, paymentStaffType, departmentId, dutyType, paymentStaffId);
                }
            }
        }

        return studentRatePayList;
    }

    @Override
    public IPage<StudentRatePay> getPayDetailListMarket(IPage<StudentRatePay> iPage, Integer yearPart, Integer
            quarterNum, String schoolId, String teacherId, String gradeId, String subjectsId, Integer type, String
                                                                startDate, String endDate, String trackId, String detailType, String lessonType, String yearClassId, String
                                                                classTypeId, Integer periodsNum, String marketTeacherId, Integer trackType, Integer classify, String
                                                                teamId, Integer isNextDateNum, AuthAdminContent authAdminContent, LeadDataRs leadDataRs) {

        //期数，1期为45，2期为90
        Integer feeCourseNum = this.getCourseNumForPeriods(periodsNum);

        Quarter quarterNow = iQuarterService.getNowQuarter();
        if (yearPart == null) {
            yearPart = quarterNow.getYearPart();
        }
        if (quarterNum == null) {
            quarterNum = quarterNow.getNum();
        }
        RenewHistoryData renewHistoryData = this.getHistoryData(yearPart, quarterNum, endDate, quarterNow);
        //是否查看历史的，1是，0否，查看历史的要使用(整个学期)历史表
        Integer isHistory = renewHistoryData.getIsHistory();
        Integer targetType = renewHistoryData.getTargetType();//0校长指标，1老师指标
        boolean dateHistory = renewHistoryData.isDateHistory();//按天看的历史数据

        Integer payYearPart = yearPart;
        Integer payQuarterNum = quarterNum;

        Integer searchYearAndQuarter = Integer.parseInt(yearPart + "" + quarterNum);
        Integer nextYearAndQuarter = 0;
        if (isHistory.equals(1) && targetType.equals(1)) {
            Integer quarterId = iQuarterService.getIdForYearPartAndNum(yearPart, quarterNum);
            Quarter nextQuater = iQuarterService.getQuarterMaxForId(quarterId + 1);//获取当前学期的两个学期后的学期
            if (nextQuater != null) {
                nextYearAndQuarter = Integer.parseInt(nextQuater.getYearPart() + "" + nextQuater.getNum());
            }
            payYearPart = quarterNow.getYearPart();
            payQuarterNum = quarterNow.getNum();
        }

        IPage<StudentRatePay> studentRatePayList = null;

        if (StringUtils.isNotBlank(teamId)) {
            String teamIdItem = trackMarketMapper.getTrackMarketChIdAll(Long.parseLong(teamId));
            if (StringUtils.isNotBlank(teamIdItem)) {
                teamId = teamIdItem;
            }
        }

        if (!dateHistory) {
            if (detailType.equals("3")) {
                if (isNextDateNum == 1) {
                    studentRatePayList = orderDetailMapper.getRatePayFeeDetailMarketV02(iPage, yearPart, quarterNum, schoolId, teacherId, gradeId, subjectsId, type, startDate, endDate, trackId, detailType, isHistory, lessonType, searchYearAndQuarter, nextYearAndQuarter, payYearPart, payQuarterNum, yearClassId, classTypeId, marketTeacherId, trackType, classify, teamId, periodsNum, authAdminContent, leadDataRs);
                } else {
                    studentRatePayList = orderDetailMapper.getRatePayFeeDetailMarket(iPage, yearPart, quarterNum, schoolId, teacherId, gradeId, subjectsId, type, startDate, endDate, trackId, detailType, isHistory, lessonType, searchYearAndQuarter, nextYearAndQuarter, payYearPart, payQuarterNum, yearClassId, classTypeId, marketTeacherId, trackType, classify, teamId, periodsNum, authAdminContent, leadDataRs);
                }
            } else {
                studentRatePayList = orderDetailMapper.getPayFeeDetailMarket(iPage, yearPart, quarterNum, schoolId, teacherId, gradeId, subjectsId, type, startDate, endDate, trackId, detailType, isHistory, lessonType, searchYearAndQuarter, nextYearAndQuarter, yearClassId, classTypeId, feeCourseNum, marketTeacherId, trackType, classify, teamId, periodsNum, authAdminContent, leadDataRs);
            }
        } else {
            if (detailType.equals("3")) {
                studentRatePayList = orderDetailMapper.getRatePayFeeDetailMarketHistory(iPage, yearPart, quarterNum, schoolId, teacherId, gradeId, subjectsId, type, startDate, endDate, trackId, detailType, isHistory, lessonType, searchYearAndQuarter, nextYearAndQuarter, payYearPart, payQuarterNum, yearClassId, classTypeId, marketTeacherId, trackType, classify, teamId, periodsNum, authAdminContent, leadDataRs);
            } else {
                studentRatePayList = orderDetailMapper.getPayFeeDetailMarketHistory(iPage, yearPart, quarterNum, schoolId, teacherId, gradeId, subjectsId, type, startDate, endDate, trackId, detailType, isHistory, lessonType, searchYearAndQuarter, nextYearAndQuarter, yearClassId, classTypeId, feeCourseNum, marketTeacherId, trackType, classify, teamId, authAdminContent, leadDataRs);
            }
        }
        return studentRatePayList;
    }


    public Integer getCourseNumForPeriods(Integer num) {
        Integer[] courseNum = new Integer[]{0, 45, 90, 135, 180, 225, 270};
        Integer name = 45;
        if (num >= 0 && num < courseNum.length) {
            name = courseNum[num];
        }
        return name;
    }


    @Override
    public List<RenewClassRecordChart> payFeeChart(Long[]
                                                           schoolId, List<YearAndQuarter> yearAndQuarterListBefore, List<YearAndQuarter> yearAndQuarterListAfter, Integer[]
                                                           quarterNum, Integer[] subjectsId, Long[] teacherId, Integer[] yearClassId, Long[] classTypeId, String type, Integer
                                                           lessonType, Integer periodsNum) {
        List<RenewClassRecordChart> renewClassRecordList = orderDetailMapper.payFeeChart(schoolId, yearAndQuarterListBefore, yearAndQuarterListAfter, quarterNum, subjectsId, teacherId, yearClassId, classTypeId, type, lessonType, periodsNum);
        for (RenewClassRecordChart renewClassRecord : renewClassRecordList) {
            renewClassRecord.setQuarterName(CommonUtil.getQuarterNameForId(renewClassRecord.getQuarterNum()));
            renewClassRecord.setYearClassName(CommonUtil.getYearClassNameForId(renewClassRecord.getYearClassId()));
        }
        return renewClassRecordList;
    }


    @Override
    public List<ResidueStatics> residueStudentCount(String schoolId, String subjectsId, Integer type, Integer
            quarterNum, String startDate, String endDate, String trackId, Integer lessonType, String yearClassId) {
        Quarter quarter = iQuarterService.getNowQuarter();

        /*QueryWrapper queryWrapper = new QueryWrapper();

        queryWrapper.eq(StringUtils.isNotBlank(subjectsId),"subjects_id",subjectsId);
        queryWrapper.eq("year_part",quarter.getYearPart());
        queryWrapper.eq("quarter_num",quarter.getNum());
        queryWrapper.eq("deleted",0);
        queryWrapper.eq("lesson_type",lessonType);
        queryWrapper.eq(StringUtils.isNotBlank(schoolId),"school_id",schoolId);*/
        List<ResidueStatics> residueStaticsList = orderDetailMapper.residueStudentCount(schoolId, quarter.getYearPart(), quarter.getNum(), subjectsId, type, lessonType, yearClassId);
        return residueStaticsList;
    }

    public IPage<ResidueStudent> residueStudentCountDetail(IPage<?> iPage, String schoolId, String
            subjectsId, String yearPart, String quarterNum, String gradeId, String teacherId, String type, Integer
                                                                   status, Integer lessonType, String yearClassId) {
        return orderDetailMapper.residueStudentCountDetail(iPage, schoolId, subjectsId, yearPart, quarterNum, gradeId, teacherId, type, status, lessonType, yearClassId);
    }


    public IPage<StudentRatePay> getPayDetailForType(IPage<?> iPage, String schoolId, String teacherId, String
            gradeId, String subjectsId, Integer type, Integer quarterNum, String detailType, Integer lessonType) {
        Quarter quarter = iQuarterService.getNowQuarter();

        //1老师，2校区老师，3校长，4校区
        List<Long> teacherSubjects = new ArrayList<>();
        if (!type.equals("4"))
            teacherSubjects = gradeMapper.getTeacherGradeSubjects(quarter.getYearPart(), quarter.getNum(), Long.parseLong(teacherId), lessonType);


        //应续人数
        //1老师，2校区老师，3校长，4校区
        QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
        orderDetailQueryWrapper.eq("deleted", 0);
        orderDetailQueryWrapper.ne("status", 2);
        orderDetailQueryWrapper.eq("year_part", quarter.getYearPart());
        orderDetailQueryWrapper.eq("quarter_num", quarter.getNum());


        if (quarter.getNum() == 2) {
            orderDetailQueryWrapper.lt("year_class_id", 9);//初三除外
        } else {
            orderDetailQueryWrapper.lt("year_class_id", 10);//包含初三
        }

        StringBuilder where02 = new StringBuilder();
        String orderDetailSql = "";
        List<String> groupBys = new ArrayList<>();
        if (type.equals(1) || type.equals(2) || type.equals(3)) {
            orderDetailSql = "select a.student_id from student_grade as a LEFT JOIN grade as b on a.grade_id = b.id where a.year_part =" + quarter.getYearPart() + " and a.quarter_num =" + quarter.getNum() + " and b.teacher_id = " + teacherId + " and a.deleted=0 and a.status in(1) and (reading_status in(1,4,5,6) or(reading_status in(3) and use_course_count>0))";
            if (StringUtils.isBlank(subjectsId)) {
                orderDetailQueryWrapper.in("subjects_id", teacherSubjects);
            }
        }

        if (type.equals(2)) {
            groupBys.add("school_id");
            orderDetailQueryWrapper.eq("school_id", schoolId);
        }
        if (type.equals(4)) {
            groupBys.add("school_id");
            orderDetailQueryWrapper.eq("school_id", schoolId);
            orderDetailSql += "select a.student_id from student_grade as a LEFT JOIN grade as b on a.grade_id = b.id where a.year_part =" + quarter.getYearPart() + " and a.quarter_num =" + quarter.getNum() + " and a.grade_id in(select id from grade where school_id=" + schoolId + ") and a.deleted=0 and a.status in(1) and (reading_status in(1,4,5,6) or(reading_status in(3) and use_course_count>0))";
        }
        if (StringUtils.isNotBlank(subjectsId)) {
            if (!type.equals(4)) {
                orderDetailSql += " and subjects_id=" + subjectsId + " ";
            }
            orderDetailQueryWrapper.eq(StringUtils.isNotBlank(subjectsId), "subjects_id", subjectsId);
        }
        //初三除外
        if (quarter.getNum() == 2) {
            orderDetailSql += " and a.year_class_id <9";
        } else {
            orderDetailSql += " and a.year_class_id <10";
        }
        if (StringUtils.isNotBlank(gradeId)) {
            orderDetailSql += " and a.grade_id =" + gradeId;
        }
        orderDetailQueryWrapper.notInSql("student_id", "select student_id from renew_no_student where deleted=0");
        orderDetailQueryWrapper.inSql("student_id", orderDetailSql);


        groupBys.add("student_id");
        groupBys.add("subjects_id");
        orderDetailQueryWrapper.groupBy(groupBys);

        IPage<StudentRatePay> studentRatePayList = null;
        if (detailType.equals("1")) {
            where02.append(" and residue_course_count >= 45");
            studentRatePayList = orderDetailMapper.getCourseCountStudent(iPage, orderDetailQueryWrapper, where02.toString());
        } else if (detailType.equals("2")) {
            where02.append(" and residue_course_count < 45");
            studentRatePayList = orderDetailMapper.getCourseCountStudent(iPage, orderDetailQueryWrapper, where02.toString());
        }

        for (StudentRatePay studentRatePay : studentRatePayList.getRecords()) {
            //Integer residueCourseCount = orderDetailMapper.getResidueCourseCount(studentRatePay.getSchoolId(),studentRatePay.getStudentId(),studentRatePay.getSubjectsId());
            //studentRatePay.setResidueCourseCount(residueCourseCount);
            boolean isInludeSchool = false;
            if (type.equals(2) || type.equals(4))
                isInludeSchool = true;
            StudentGrade studentGrade = iStudentGradeService.getLastStudentGradeForOrderDetailId(studentRatePay.getSchoolId(), studentRatePay.getStudentId(), studentRatePay.getSubjectsId(), quarter.getYearPart(), quarter.getNum(), isInludeSchool, lessonType);
            if (studentGrade != null) {
                Grade grade = iGradeService.getById(studentGrade.getGradeId());
                if (grade != null) {
                    studentRatePay.setGradeId(grade.getId());
                    studentRatePay.setGradeName(grade.getName());
                    studentRatePay.setTeacherId(grade.getTeacherId());
                    Staff staff = iStaffService.getById(grade.getTeacherId());
                    if (staff != null) {
                        studentRatePay.setTeacherName(staff.getName());
                    }
                }
            }
        }
        return studentRatePayList;
    }


    /**
     * 续报率
     *
     * @param subjectsId
     * @param type
     * @param quarterNum
     * @param startDate
     * @param endDate
     * @param trackId
     * @return
     * @throws ParseException
     */
    @Override
    public List<ContinueInfo> getContinueFee(Integer yearPart,
                                             Integer quarterNum,
                                             String schoolId,
                                             String subjectsId,
                                             Integer type,
                                             String startDate,
                                             String endDate,
                                             String trackId,
                                             Integer lessonType,
                                             String yearClassId,
                                             String classTypeId,
                                             String name,
                                             AuthAdminContent authAdminContent,
                                             LeadDataRs leadDataRs,
                                             Integer versionNum,
                                             Integer paymentStaff,
                                             Integer paymentStaffType,
                                             Integer isDetails,
                                             String teacherId) throws
            ParseException {

        /*QueryWrapper queryWrapper = new QueryWrapper();

        queryWrapper.eq(StringUtils.isNotBlank(subjectsId),"subjects_id",subjectsId);
        queryWrapper.eq("year_part",quarter.getYearPart());
        queryWrapper.eq("quarter_num",quarter.getNum());
        queryWrapper.eq("deleted",0);
        queryWrapper.eq("lesson_type",lessonType);

        List<ContinueInfo> renewClassRecordList = null;
        List<String> groupBys = new ArrayList<>();
        //1老师，2校区老师，3校长，4校区
        if(type.equals(1)){
            groupBys.add("teacher_id");
            if (StringUtils.isNotBlank(trackId)){
 queryWrapper.inSql("teacher_id","select sourse_id from track_detail where deleted = 0 and track_id ="+trackId);
            }
        }else if(type.equals(2)){
            groupBys.add("school_id");
            groupBys.add("teacher_id");
            queryWrapper.eq(StringUtils.isNotBlank(schoolId),"school_id",schoolId);
        }else if(type.equals(3)){
            queryWrapper.inSql("teacher_id","select admin_id from role_admin where role_id = 1568160887369994242 ");
            groupBys.add("teacher_id");

        }else if(type.equals(4)){
            groupBys.add("school_id");
            if (StringUtils.isNotBlank(trackId)){
 queryWrapper.inSql("school_id","select sourse_id from track_detail where deleted = 0 and track_id ="+trackId);
            }
        }
        groupBys.add("quarter_num");
        if(StringUtils.isNotBlank(subjectsId)){
            groupBys.add("subjects_id");
        }
        queryWrapper.groupBy(groupBys);

        if (type.equals(1)){
            renewClassRecordList =  teacherContinueInfoMapper.getRenewRecordPerson(queryWrapper);
        }else if (type.equals(2)){
            renewClassRecordList =  teacherContinueInfoMapper.getRenewRecord(queryWrapper);
        }else if (type.equals(3)){
            renewClassRecordList =  teacherContinueInfoMapper.getRenewRecordPerson(queryWrapper);
        }else if (type.equals(4)){
            renewClassRecordList =  teacherContinueInfoMapper.getRenewRecordSchool(queryWrapper);
        }

        List<Long> teacherSubjects  = new ArrayList<>();

        for (ContinueInfo continueInfo :renewClassRecordList){
            QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
            teacherSubjects = gradeMapper.getTeacherGradeSubjects(quarter.getYearPart(),quarter.getNum(),continueInfo.getTeacherId(),lessonType);

            //1老师，2校区老师，3校长，4校区
            if(type.equals(1)){
 studentGradeQueryWrapper.inSql("grade_id","select id from grade where teacher_id = "+continueInfo.getTeacherId()+"");
            }else if(type.equals(2)){
 studentGradeQueryWrapper.eq("school_id",continueInfo.getSchoolId());
 studentGradeQueryWrapper.inSql("grade_id","select id from grade where school_id = "+continueInfo.getSchoolId()+" and teacher_id = "+continueInfo.getTeacherId()+"");
            }else if(type.equals(3)){
 studentGradeQueryWrapper.inSql("grade_id","select id from grade where teacher_id = "+continueInfo.getTeacherId()+"");
            }else if(type.equals(4)){
 studentGradeQueryWrapper.eq("school_id",continueInfo.getSchoolId());
            }

            studentGradeQueryWrapper.eq(StringUtils.isNotBlank(subjectsId),"subjects_id",subjectsId);
            studentGradeQueryWrapper.eq("year_part",quarter.getYearPart());
            studentGradeQueryWrapper.eq("quarter_num",quarter.getNum());
            studentGradeQueryWrapper.eq("deleted",0);
            studentGradeQueryWrapper.in("status",1);
            studentGradeQueryWrapper.eq("lesson_type",lessonType);
            //studentGradeQueryWrapper.ne("reading_status",2);
            studentGradeQueryWrapper.and(i->i.in("reading_status",1,4,5,6).or(j->j.in("reading_status",3).gt("use_course_count",0)));

            if (quarter.getNum() == 2){
 studentGradeQueryWrapper.lt("year_class_id",9);//初三除外
            }else {
 studentGradeQueryWrapper.lt("year_class_id",10);//包含初三
            }
            studentGradeQueryWrapper.notInSql("student_id","select student_id from renew_no_student where deleted=0");
            //获取带班总人数
            Integer studentAllCount = renewClassMapper.getStudentAllCount(studentGradeQueryWrapper);
            continueInfo.setStudentAllCount(studentAllCount);

            //获取总已排班人数
            QueryWrapper<TeacherContinueInfo> teacherContinueInfoQueryWrapper = new QueryWrapper<>();
            teacherContinueInfoQueryWrapper.eq("deleted",0);
            teacherContinueInfoQueryWrapper.eq("status",1);
            if (quarter.getNum() == 2){
 teacherContinueInfoQueryWrapper.lt("year_class_id",10);//高一除外
            }else {
 teacherContinueInfoQueryWrapper.lt("year_class_id",11);//包含高一
            }
            if(type.equals(1) || type.equals(2) ||type.equals(3)){
 teacherContinueInfoQueryWrapper.eq("teacher_id",continueInfo.getTeacherId());
 if(StringUtils.isBlank(subjectsId)){
     teacherContinueInfoQueryWrapper.in("subjects_id",teacherSubjects);
 }
            }
            if(type.equals(2)){
 groupBys.add("school_id");
 teacherContinueInfoQueryWrapper.eq("school_id",continueInfo.getSchoolId());
            }
            if(type.equals(4)){
 groupBys.add("school_id");
 teacherContinueInfoQueryWrapper.eq("school_id",continueInfo.getSchoolId());
            }
            if(StringUtils.isNotBlank(subjectsId)){
 teacherContinueInfoQueryWrapper.eq(StringUtils.isNotBlank(subjectsId),"subjects_id",subjectsId);
            }
            groupBys = new ArrayList<>();
            groupBys.add("student_id");
            groupBys.add("subjects_id");
            teacherContinueInfoQueryWrapper.groupBy(groupBys);
            teacherContinueInfoQueryWrapper.notInSql("student_id","select student_id from renew_no_student where deleted=0");
            continueInfo.setSchedulingCount(teacherContinueInfoMapper.getContinueInfoCount(teacherContinueInfoQueryWrapper));

            teacherContinueInfoQueryWrapper.ge(StringUtils.isNotBlank(startDate),"add_date",startDate);
            teacherContinueInfoQueryWrapper.le(StringUtils.isNotBlank(endDate),"add_date",endDate);
            continueInfo.setDateSchedulingCount(teacherContinueInfoMapper.getContinueInfoCount(teacherContinueInfoQueryWrapper));
            if (studentAllCount>0){
 BigDecimal continueRate = new BigDecimal(continueInfo.getSchedulingCount()).divide(new BigDecimal(studentAllCount),2, RoundingMode.HALF_UP).multiply(new BigDecimal(100));
 continueInfo.setContinueRate(continueRate);
            }else {
 continueInfo.setContinueRate(new BigDecimal(0));
            }

        }*/

        Quarter nextQuarter = CommonUtil.getNextQuarter(yearPart, quarterNum);
        Integer nextYearPart = nextQuarter.getYearPart();
        Integer nextQuarterNum = nextQuarter.getNum();

        List<ContinueInfo> continueInfoList = new ArrayList<>();

        // 获取是否为历史数据
        Integer isHistory = 0;
        if (StringUtils.isNotBlank(endDate)) {
            // 如果结束日期小于当前日期，那么为历史数据
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate endLocalDate = LocalDate.parse(endDate, formatter);
            if (endLocalDate.isBefore(LocalDate.now())) {
                isHistory = 1;
            }
        }

        if (versionNum.equals(1)) {
            continueInfoList = teacherContinueInfoMapper.getRenewRecord(schoolId, yearPart, quarterNum, nextYearPart, nextQuarterNum, subjectsId, type, startDate, endDate, lessonType, trackId, yearClassId, classTypeId, name, authAdminContent, leadDataRs, isHistory);

            for (ContinueInfo continueInfo : continueInfoList) {
                if (continueInfo.getStudentAllCount() > 0) {
                    BigDecimal continueRate = new BigDecimal(continueInfo.getSchedulingCount()).divide(new BigDecimal(continueInfo.getStudentAllCount()), 4, RoundingMode.HALF_UP).multiply(new BigDecimal(100));
                    continueInfo.setContinueRate(continueRate);
                } else {
                    continueInfo.setContinueRate(new BigDecimal(0));
                }
            }

            if (type == 6) {

                List<ContinueInfo> collectList = new ArrayList<>();

                QueryWrapper queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("year_part", yearPart);
                queryWrapper.eq("quarter_num", quarterNum);
                queryWrapper.eq("pid", 0);
                List<SchoolQuarter> schoolQuarterList = iSchoolQuarterService.list(queryWrapper);

                for (SchoolQuarter schoolQuarter : schoolQuarterList) {
                    ContinueInfo practicePlanStaff = new ContinueInfo();
                    practicePlanStaff.setSchoolId(schoolQuarter.getSchoolId());
                    practicePlanStaff.setSchoolName(schoolQuarter.getSchoolName());
                    practicePlanStaff.setSchoolPid(schoolQuarter.getPid());
                    practicePlanStaff.setStudentAllCount(0);
                    practicePlanStaff.setSchedulingCount(0);
                    practicePlanStaff.setDateSchedulingCount(0);

                    collectList.add(practicePlanStaff);
                }

                for (ContinueInfo practicePlanStaff : collectList) {
                    List<ContinueInfo> childRates = new ArrayList<>();
                    for (ContinueInfo planStaff : continueInfoList) {
                        if (practicePlanStaff.getSchoolId().equals(planStaff.getSchoolId()) || practicePlanStaff.getSchoolId().equals(planStaff.getSchoolPid())) {
                            childRates.add(planStaff);
                            if (planStaff.getStudentAllCount() != null) {
                                practicePlanStaff.setStudentAllCount(practicePlanStaff.getStudentAllCount() + planStaff.getStudentAllCount());
                            }
                            if (planStaff.getSchedulingCount() != null) {
                                practicePlanStaff.setSchedulingCount(practicePlanStaff.getSchedulingCount() + planStaff.getSchedulingCount());
                            }
                            if (planStaff.getDateSchedulingCount() != null) {
                                practicePlanStaff.setDateSchedulingCount(practicePlanStaff.getDateSchedulingCount() + planStaff.getDateSchedulingCount());
                            }
                        }
                    }
                    practicePlanStaff.setChildren(childRates);
                }

                continueInfoList = collectList;
            }
        } else if (versionNum.equals(2)) {

            String departmentId = "0";
            Integer dutyType = 0;

            if (paymentStaff.equals(1)) {
                // 教学主管
                departmentId = "23";
                dutyType = 1;
            } else if (paymentStaff.equals(2)) {
                // 市场
                departmentId = "27";
                dutyType = 1;
            } else if (paymentStaff.equals(3)) {
                // 年级负责人
                departmentId = "23";
                dutyType = 2;
            } else if (paymentStaff.equals(6)) {
                // 小校区主管
                departmentId = "24,25";
                dutyType = 1;
            }

            continueInfoList = teacherContinueInfoMapper.getRenewRecordV2(schoolId, yearPart, quarterNum, nextYearPart, nextQuarterNum, subjectsId, type, startDate, endDate, lessonType, trackId, yearClassId, classTypeId, name, authAdminContent, leadDataRs, paymentStaff, paymentStaffType, departmentId, dutyType, isDetails, teacherId, isHistory);

            if (paymentStaffType != 4) {
                if (continueInfoList.size() > 0) {
                    Map<Object, ContinueInfo> mergedMap = new HashMap<>();
                    for (ContinueInfo record : continueInfoList) {

                        ContinueInfo mergedRecord = mergedMap.get(record.getTeacherId());
                        if (mergedRecord == null) {
                            mergedRecord = new ContinueInfo();
                            mergedRecord.setTeacherId(record.getTeacherId());
                            mergedRecord.setTeacherName(record.getTeacherName());
                            mergedRecord.setSchoolPid(record.getSchoolPid());
                            mergedRecord.setStudentAllCount(0);
                            mergedRecord.setSchedulingCount(0);
                            mergedRecord.setDateSchedulingCount(0);
                            mergedRecord.setChildren(new ArrayList<>());
                            mergedMap.put(record.getTeacherId(), mergedRecord);
                        }

                        mergedRecord.getChildren().add(record);

                        if (record.getStudentAllCount() != null) {
                            mergedRecord.setStudentAllCount(mergedRecord.getStudentAllCount() + record.getStudentAllCount());
                        }
                        if (record.getSchedulingCount() != null) {
                            mergedRecord.setSchedulingCount(mergedRecord.getSchedulingCount() + record.getSchedulingCount());
                        }
                        if (record.getDateSchedulingCount() != null) {
                            mergedRecord.setDateSchedulingCount(mergedRecord.getDateSchedulingCount() + record.getDateSchedulingCount());
                        }
                    }

                    continueInfoList.clear();
                    continueInfoList.addAll(mergedMap.values());
                }
            }
        }

        return continueInfoList;
    }

    @Override
    public IPage<ContinueInfo> getContinueFeeDetail(IPage<?> iPage,
                                                    Integer yearPart,
                                                    Integer quarterNum,
                                                    String schoolId,
                                                    String subjectsId,
                                                    Integer type,
                                                    String startDate,
                                                    String endDate,
                                                    Integer lessonType,
                                                    String teacherId,
                                                    String gradeId,
                                                    String yearClassId,
                                                    String classTypeId,
                                                    AuthAdminContent authAdminContent,
                                                    LeadDataRs leadDataRs,
                                                    Integer paymentStaff,
                                                    Integer paymentStaffType,
                                                    Integer versionNum,
                                                    String paymentStaffId,
                                                    Integer detailType
    ) throws ParseException {
        Quarter nextQuarter = CommonUtil.getNextQuarter(yearPart, quarterNum);
        Integer nextYearPart = nextQuarter.getYearPart();
        Integer nextQuarterNum = nextQuarter.getNum();

        IPage<ContinueInfo> continueInfoIPage = new Page<>();

        // 获取是否为历史数据
        Integer isHistory = 0;
        if (StringUtils.isNotBlank(endDate)) {
            // 如果结束日期小于当前日期，那么为历史数据
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate endLocalDate = LocalDate.parse(endDate, formatter);
            if (endLocalDate.isBefore(LocalDate.now())) {
                isHistory = 1;
            }
        }

        if (versionNum.equals(1)) {

            continueInfoIPage = teacherContinueInfoMapper.getRenewRecordDetail(iPage, schoolId, yearPart, quarterNum, nextYearPart, nextQuarterNum, subjectsId, type, startDate, endDate, lessonType, teacherId, gradeId, yearClassId, classTypeId, authAdminContent, leadDataRs, isHistory, detailType);

        } else if (versionNum.equals(2)) {
            String departmentId = "0";
            Integer dutyType = 0;

            if (paymentStaff.equals(1)) {
                // 教学主管
                departmentId = "23";
                dutyType = 1;
            } else if (paymentStaff.equals(2)) {
                // 市场
                departmentId = "27";
                dutyType = 1;
            } else if (paymentStaff.equals(3)) {
                // 年级负责人
                departmentId = "23";
                dutyType = 2;
            } else if (paymentStaff.equals(6)) {
                // 小校区主管
                departmentId = "24,25";
                dutyType = 1;
            }

            continueInfoIPage = teacherContinueInfoMapper.getRenewRecordDetailV2(iPage, schoolId, yearPart, quarterNum, nextYearPart, nextQuarterNum, subjectsId, type, startDate, endDate, lessonType, teacherId, gradeId, yearClassId, classTypeId, authAdminContent, leadDataRs, paymentStaff, paymentStaffType, departmentId, dutyType, paymentStaffId, isHistory, detailType);
        }

        return continueInfoIPage;
    }


    public IPage<StudentRatePay> getContinueFeeDetailForType(IPage<?> iPage, String schoolId, String
            teacherId, String gradeId, String subjectsId, Integer type, Integer quarterNum, String detailType, Integer
                                                                     lessonType) {
        Quarter quarter = iQuarterService.getNowQuarter();

        //1老师，2校区老师，3校长，4校区
        List<Long> teacherSubjects = new ArrayList<>();
        if (!type.equals("4"))
            teacherSubjects = gradeMapper.getTeacherGradeSubjects(quarter.getYearPart(), quarter.getNum(), Long.parseLong(teacherId), lessonType);


        //应续人数
        //1老师，2校区老师，3校长，4校区
        QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
        orderDetailQueryWrapper.eq("deleted", 0);
        orderDetailQueryWrapper.ne("status", 2);

        if (quarter.getNum() == 2) {
            orderDetailQueryWrapper.lt("year_class_id", 9);//初三除外
        } else {
            orderDetailQueryWrapper.lt("year_class_id", 10);//包含初三
        }

        StringBuilder where02 = new StringBuilder();
        String orderDetailSql = "";
        List<String> groupBys = new ArrayList<>();
        if (type.equals(1) || type.equals(2) || type.equals(3)) {
            orderDetailSql = "select a.student_id from student_grade as a LEFT JOIN grade as b on a.grade_id = b.id where a.year_part =" + quarter.getYearPart() + " and a.quarter_num =" + quarter.getNum() + " and b.teacher_id = " + teacherId + " and a.deleted=0 and a.status in(1) and (reading_status in(1,4,5,6) or(reading_status in(3) and use_course_count>0))";
            if (StringUtils.isBlank(subjectsId)) {
                orderDetailQueryWrapper.in("subjects_id", teacherSubjects);
            }
        }

        if (type.equals(2)) {
            groupBys.add("school_id");
            orderDetailQueryWrapper.eq("school_id", schoolId);
        }
        if (type.equals(4)) {
            groupBys.add("school_id");
            orderDetailQueryWrapper.eq("school_id", schoolId);
            orderDetailSql += "select a.student_id from student_grade as a LEFT JOIN grade as b on a.grade_id = b.id where a.year_part =" + quarter.getYearPart() + " and a.quarter_num =" + quarter.getNum() + " and a.school_id=" + schoolId + " and a.deleted=0 and a.status in(1) and (reading_status in(1,4,5,6) or(reading_status in(3) and use_course_count>0))";
        }
        if (StringUtils.isNotBlank(subjectsId)) {
            if (!type.equals(4)) {
                orderDetailSql += " and subjects_id=" + subjectsId + " ";
            }
            orderDetailQueryWrapper.eq(StringUtils.isNotBlank(subjectsId), "subjects_id", subjectsId);
        }
        //初三除外
        if (quarter.getNum() == 2) {
            orderDetailSql += " and a.year_class_id <9";
        } else {
            orderDetailSql += " and a.year_class_id <10";
        }
        if (StringUtils.isNotBlank(gradeId)) {
            orderDetailSql += " and a.grade_id =" + gradeId;
        }

        orderDetailQueryWrapper.inSql("student_id", orderDetailSql);


        groupBys.add("student_id");
        groupBys.add("subjects_id");
        orderDetailQueryWrapper.groupBy(groupBys);
        orderDetailQueryWrapper.notInSql("student_id", "select student_id from renew_no_student where deleted=0");

        IPage<StudentRatePay> studentRatePayList = null;
        if (detailType.equals("1")) {
            where02.append(" and residue_course_count >= 45");
            studentRatePayList = orderDetailMapper.getCourseCountStudent(iPage, orderDetailQueryWrapper, where02.toString());
        } else if (detailType.equals("2")) {
            where02.append(" and residue_course_count < 45");
            studentRatePayList = orderDetailMapper.getCourseCountStudent(iPage, orderDetailQueryWrapper, where02.toString());
        }

        for (StudentRatePay studentRatePay : studentRatePayList.getRecords()) {
            //Integer residueCourseCount = orderDetailMapper.getResidueCourseCount(studentRatePay.getSchoolId(),studentRatePay.getStudentId(),studentRatePay.getSubjectsId());
            //studentRatePay.setResidueCourseCount(residueCourseCount);
            boolean isInludeSchool = false;
            if (type.equals(2) || type.equals(4))
                isInludeSchool = true;
            StudentGrade studentGrade = iStudentGradeService.getLastStudentGradeForOrderDetailId(studentRatePay.getSchoolId(), studentRatePay.getStudentId(), studentRatePay.getSubjectsId(), quarter.getYearPart(), quarter.getNum(), isInludeSchool, lessonType);
            if (studentGrade != null) {
                Grade grade = iGradeService.getById(studentGrade.getGradeId());
                if (grade != null) {
                    studentRatePay.setGradeId(grade.getId());
                    studentRatePay.setGradeName(grade.getName());
                    studentRatePay.setTeacherId(grade.getTeacherId());
                    Staff staff = iStaffService.getById(grade.getTeacherId());
                    if (staff != null) {
                        studentRatePay.setTeacherName(staff.getName());
                    }
                }
            }
        }
        return studentRatePayList;
    }

    public List<RenewClassRecord> getDataSummary(DataSummaryList dataSummaryList) {
        Quarter quarterNow = iQuarterService.getNowQuarter();
        //期数，1期为45，2期为90
        Integer feeCourseNum = this.getCourseNumForPeriods(dataSummaryList.getPeriodsNum());
        if (dataSummaryList.getYearPart() == null) {
            dataSummaryList.setYearPart(quarterNow.getYearPart());
        }
        if (dataSummaryList.getQuarterNum() == null) {
            dataSummaryList.setQuarterNum(quarterNow.getNum());
        }

        //是否查看历史的，1是，0否
        Integer isHistory = 0;
        if (!quarterNow.getYearPart().equals(dataSummaryList.getYearPart()) || !quarterNow.getNum().equals(dataSummaryList.getQuarterNum())) {
            isHistory = 1;
        }

        Integer payYearPart = dataSummaryList.getYearPart();
        Integer payQuarterNum = dataSummaryList.getQuarterNum();

        Integer searchYearAndQuarter = Integer.parseInt(dataSummaryList.getYearPart() + "" + dataSummaryList.getQuarterNum());
        Integer nextYearAndQuarter = 0;
        if (isHistory.equals(1) && dataSummaryList.getStartDate() != null && LocalDate.parse(dataSummaryList.getStartDate()).equals(LocalDate.now())) {
            Integer quarterId = iQuarterService.getIdForYearPartAndNum(dataSummaryList.getYearPart(), dataSummaryList.getQuarterNum());
            Quarter nextQuater = iQuarterService.getQuarterMaxForId(quarterId + 1);//获取当前学期的下个学期后的学期
            if (nextQuater != null) {
                nextYearAndQuarter = Integer.parseInt(nextQuater.getYearPart() + "" + nextQuater.getNum());
            }
            payYearPart = quarterNow.getYearPart();
            payQuarterNum = quarterNow.getNum();
        }

        StringBuilder sql = new StringBuilder();
        if (dataSummaryList.getIsType() == 1) {
            for (int i = 0; i < ConfigData.yearClassNameArr.length; i++) {
                if (sql.length() > 0) {
                    sql.append("union all");
                }

                sql.append(getDataSummarySql(dataSummaryList, feeCourseNum, isHistory, payYearPart, payQuarterNum, searchYearAndQuarter, nextYearAndQuarter, i));
            }
        } else {
            sql.append(getDataSummarySql(dataSummaryList, feeCourseNum, isHistory, payYearPart, payQuarterNum, searchYearAndQuarter, nextYearAndQuarter, null));
        }
        // studentAllCount 总应缴; bigFifteen 总已缴; littleFifteen 总未缴; payNum 已缴; 总已缴 / 总应缴 = percentage 缴费率
        return orderDetailMapper.getDataSummary(sql.toString());
    }

    /**
     * 市场续报率
     */
    @Override
    public List<ContinueInfo> getContinueFeeMarket(Integer yearPart, Integer quarterNum, String schoolId, String
            subjectsId, String startDate, String endDate, Integer lessonType, String yearClassId, String
                                                           classTypeId, Integer classify, Integer trackType, String trackId) throws ParseException {
        Quarter nextQuarter = CommonUtil.getNextQuarter(yearPart, quarterNum);
        Integer nextYearPart = nextQuarter.getYearPart();
        Integer nextQuarterNum = nextQuarter.getNum();

        List<ContinueInfo> continueInfoList = teacherContinueInfoMapper.getRenewRecordMarket(schoolId, yearPart, quarterNum, nextYearPart, nextQuarterNum, subjectsId, startDate, endDate, lessonType, yearClassId, classTypeId, classify, trackType, trackId);
        for (ContinueInfo continueInfo : continueInfoList) {
            if (continueInfo.getStudentAllCount() > 0) {
                BigDecimal continueRate = new BigDecimal(continueInfo.getSchedulingCount()).divide(new BigDecimal(continueInfo.getStudentAllCount()), 4, RoundingMode.HALF_UP).multiply(new BigDecimal(100));
                continueInfo.setContinueRate(continueRate);
            } else {
                continueInfo.setContinueRate(new BigDecimal(0));
            }
        }
        return continueInfoList;
    }

    /**
     * 市场续报率详情
     */
    @Override
    public IPage<ContinueInfo> getContinueFeeDetailMarket(IPage<?> iPage, Integer yearPart, Integer
            quarterNum, String schoolId, String subjectsId, String startDate, String endDate, Integer lessonType, String
                                                                  teamId, String gradeId, String yearClassId, String classTypeId, Integer classify, Integer trackType, String
                                                                  trackId) throws ParseException {
        Quarter nextQuarter = CommonUtil.getNextQuarter(yearPart, quarterNum);
        Integer nextYearPart = nextQuarter.getYearPart();
        Integer nextQuarterNum = nextQuarter.getNum();

        return teacherContinueInfoMapper.getRenewRecordDetailMarket(iPage, schoolId, yearPart, quarterNum, nextYearPart, nextQuarterNum, subjectsId, startDate, endDate, lessonType, teamId, gradeId, yearClassId, classTypeId, classify, trackType, trackId);
    }

    @Override
    public IPage<ContinueInfo> getRenewRecordDetailMarketBySourseId(IPage<?> iPage, Integer yearPart, Integer
            quarterNum, String schoolId, String subjectsId, String startDate, String endDate, Integer lessonType, String
                                                                            teamId, String gradeId, String yearClassId, String classTypeId, String sourseId, String detailType, Integer
                                                                            classify, Integer trackType, String trackId, AuthAdminContent authAdminContent, LeadDataRs leadDataRs) throws
            ParseException {
        Quarter nextQuarter = CommonUtil.getNextQuarter(yearPart, quarterNum);
        Integer nextYearPart = nextQuarter.getYearPart();
        Integer nextQuarterNum = nextQuarter.getNum();

        return teacherContinueInfoMapper.getRenewRecordDetailMarketBySourseId(iPage, schoolId, yearPart, quarterNum, nextYearPart, nextQuarterNum, subjectsId, startDate, endDate, lessonType, teamId, gradeId, yearClassId, classTypeId, sourseId, detailType, classify, trackType, trackId, authAdminContent, leadDataRs);
    }

    private String getDataSummarySql(DataSummaryList dataSummaryList, Integer feeCourseNum, Integer
            isHistory, Integer payYearPart, Integer payQuarterNum, Integer searchYearAndQuarter, Integer
                                             nextYearAndQuarter, Integer i) {
        StringBuilder sql = new StringBuilder();
        sql.append("(SELECT * FROM (SELECT *,DENSE_RANK() OVER ( ORDER BY MAX( ");
        //1已缴；2总已缴；3缴费率
        if (dataSummaryList.getPaymentStatus() == 1) {
            sql.append(" payNum ");
        }
        if (dataSummaryList.getPaymentStatus() == 2) {
            sql.append(" bigFifteen ");
        }
        if (dataSummaryList.getPaymentStatus() == 3) {
            sql.append(" percentage ");
        }
        sql.append(" ) DESC ) AS ranking FROM (")
                .append("(SELECT " + "count( id ) AS studentAllCount, " + "SUM( CASE WHEN residue_course_count_all >= ").append(feeCourseNum).append(" THEN 1 ELSE 0 END ) AS bigFifteen, ")
                .append("(SUM( CASE WHEN residue_course_count_all >= ").append(feeCourseNum).append(" THEN 1 ELSE 0 END ) / count( id ) * 100) AS percentage, ")
                .append("SUM( CASE WHEN residue_course_count_all < ").append(feeCourseNum).append(" THEN 1 ELSE 0 END ) AS littleFifteen, ")
                .append("teacher_id, ")
                .append("year_class_id, ")
                .append("getStaffNameForId ( teacher_id ) AS teacherName, ")
                .append("school_id, ")
                .append("getSchoolName ( school_id ) AS schoolName, ")
                .append("subjects_id, ")
                .append("getSubjectsName ( subjects_id ) AS subjects_name, ")
                .append("( ")
                .append("SELECT ")
                .append("IFNULL( sum( num ), 0 ) AS all_num  ")
                .append("FROM ")
                .append("( ")
                .append("SELECT ")
                .append("sum( num ) AS num  ")
                .append("FROM ")
                .append("rate_pay_view  ")
                .append("WHERE ")
                .append("deleted = 0  ")
                .append("AND STATUS = 1  ")
                .append("AND year_part = ").append(payYearPart).append("  ")
                .append("AND quarter_num = ").append(payQuarterNum).append("  ")
                .append("AND lesson_type = t3.lesson_type  ");
        if (i != null) {
            sql.append("AND year_class_id = ").append(i).append(" ");
        }
        if (dataSummaryList.getClassTypeId() != null && !dataSummaryList.getClassTypeId().isEmpty()) {
            sql.append("AND course_type_id IN ( ").append(dataSummaryList.getClassTypeId()).append(" )  ");
        }
        if (dataSummaryList.getStartDate() != null && !dataSummaryList.getStartDate().isEmpty()) {
            sql.append("AND add_date >= '").append(dataSummaryList.getStartDate()).append("'  ");
        }
        if (dataSummaryList.getEndDate() != null && !dataSummaryList.getEndDate().isEmpty()) {
            sql.append("AND add_date <= '").append(dataSummaryList.getEndDate()).append("'  ");
        }
        sql.append("AND student_id NOT IN ( SELECT student_id FROM renew_no_student WHERE deleted = 0 AND year_part = ").append(dataSummaryList.getYearPart()).append(" AND quarter_num = ").append(dataSummaryList.getQuarterNum()).append(" )  ")
                .append("AND teacher_id = t3.teacher_id  ")
                .append("AND subjects_id = t3.subjects_id  ")
                .append(") AS t_rate_pay  ")
                .append(") AS payNum  ")
                .append("FROM ")
                .append("( ")
                .append("SELECT ")
                .append("id, ")
                .append("school_id, ")
                .append("teacher_id, ")
                .append("student_id, ")
                .append("subjects_id, ")
                .append("year_part, ")
                .append("quarter_num, ")
                .append("grade_id, ")
                .append("lesson_type, ")
                .append("year_class_id, ")
                .append("course_type_id, ")
                .append("residue_course_count_all  ")
                .append("FROM ")
                .append("( ")
                .append("SELECT ")
                .append("t1.*, ")
                .append("sum( ")
                .append("IFNULL( t2.residue_course_count, 0 ) + IFNULL( t6.all_course_count, 0 )) AS residue_course_count_all  ")
                .append("FROM ")
                .append("student_grade_view AS t1 ")
                .append("LEFT JOIN ");
        if (isHistory == 0) {
            sql.append("order_detail ");
        }
        if (isHistory == 1) {
            sql.append("order_detail_history ");
        }
        sql.append(" AS t2 ON t2.student_id = t1.student_id  ")
                .append("AND t2.school_id = t1.school_id  ")
                .append("AND t2.subjects_id = t1.subjects_id  ")
                .append("AND t2.year_part = t1.year_part  ")
                .append("AND t2.lesson_type = t1.lesson_type  ")
                .append("AND t2.quarter_num = t1.quarter_num  ")
                .append("AND t2.`status` <> 2  ")
                .append("AND t2.deleted = 0 ")
                .append("LEFT JOIN order_detail AS t6 ON t6.student_id = t1.student_id  ")
                .append("AND t6.school_id = t1.school_id  ")
                .append("AND t6.subjects_id = t1.subjects_id  ")
                .append("AND t6.lesson_type = t1.lesson_type  ")
                .append("AND t6.year_and_quarter > ").append(searchYearAndQuarter).append("  ")
                .append("AND t6.year_and_quarter <= ").append(nextYearAndQuarter).append("  ")
                .append("AND t6.STATUS <> 2  ")
                .append("AND t6.deleted = 0  ")
                .append("AND t6.order_type = 1  ")
                .append("WHERE ")
                .append("t1.year_part = ").append(dataSummaryList.getYearPart()).append("  ")
                .append("AND t1.quarter_num = ").append(dataSummaryList.getQuarterNum()).append("  ")
                .append("AND t1.is_last = 1  ")
                .append("AND t1.is_makeup = 0  ")
                .append("AND t1.deleted = 0  ")
                .append("AND t1.`status` = 1  ")
                .append("AND t1.lesson_type = ").append(dataSummaryList.getLessonType()).append("  ")
                .append("AND ( ")
                .append("t1.reading_status IN ( 1, 4, 5, 6 )  ")
                .append("OR ( t1.reading_status = 3 AND t1.use_course_count > 0 ))  ")
                .append("AND t1.student_id NOT IN ( SELECT student_id FROM renew_no_student WHERE deleted = 0 AND year_part = ").append(dataSummaryList.getYearPart()).append(" AND quarter_num = ").append(dataSummaryList.getQuarterNum()).append(" )  ");
        if (i != null) {
            sql.append("AND t1.year_class_id = ").append(i).append("  ");
        }
        if (dataSummaryList.getClassTypeId() != null && !dataSummaryList.getClassTypeId().isEmpty()) {
            sql.append("AND t1.course_type_id IN ( ").append(dataSummaryList.getClassTypeId()).append(" )  ");
        }
        if (dataSummaryList.getSubjectsId() != null && !dataSummaryList.getSubjectsId().isEmpty()) {
            sql.append("AND t1.subjects_id IN ( ").append(dataSummaryList.getSubjectsId()).append(" ) ");
        }
        if (dataSummaryList.getSchoolId() != null && !dataSummaryList.getSchoolId().isEmpty()) {
            sql.append("AND t1.school_id IN ( ").append(dataSummaryList.getSchoolId()).append(" )  ");
        }
        if (dataSummaryList.getTrackId() != null && !dataSummaryList.getTrackId().isEmpty() && dataSummaryList.getType() == 1) {
            sql.append("AND t1.teacher_id in(select sourse_id from track_detail where deleted = 0 and track_id = ").append(dataSummaryList.getSubjectsId()).append(")  ");
        }
        if (dataSummaryList.getTrackId() != null && !dataSummaryList.getTrackId().isEmpty() && dataSummaryList.getType() == 4) {
            sql.append("AND t1.school_id in(select sourse_id from track_detail where deleted = 0 and track_id = ").append(dataSummaryList.getSubjectsId()).append(")  ");
        }
        if (dataSummaryList.getType() == 3) {
            sql.append("AND t1.teacher_id in(select admin_id from role_admin where role_id = 1568160887369994242) ");
        }
        sql.append("GROUP BY ").append("t1.school_id, ").append("t1.student_id, ").append("t1.subjects_id, ").append("t1.teacher_id  ")
                .append(") AS t  ")
                .append(") AS t3  ");
        if (dataSummaryList.getType() == 1 || dataSummaryList.getType() == 3) {
            sql.append("GROUP BY teacher_id");
        }
        if (dataSummaryList.getType() == 2) {
            sql.append("GROUP BY school_id,teacher_id");
        }
        if (dataSummaryList.getType() == 4) {
            sql.append("GROUP BY school_id");
        }
        sql.append(")) AS fff ");
        if (dataSummaryList.getType() == 1 || dataSummaryList.getType() == 3) {
            sql.append("GROUP BY teacher_id");
        }
        if (dataSummaryList.getType() == 2) {
            sql.append("GROUP BY school_id,teacher_id");
        }
        if (dataSummaryList.getType() == 4) {
            sql.append("GROUP BY school_id");
        }
        sql.append(" ORDER BY ranking ASC ) AS ttt WHERE ranking <= ").append(dataSummaryList.getSeeRows()).append(") ");
        return sql.toString();
    }


    public RenewHistoryData getHistoryData(Integer yearPart, Integer quarterNum, String endDate, Quarter quarterNow) {

        RenewHistoryData renewHistoryData = new RenewHistoryData();
        LocalDate endDateFormat = LocalDate.parse(endDate);
        LocalDate dateNow = LocalDate.now();
        //是否查看历史的，1是，0否，查看历史的要使用(整个学期)历史表
        Integer isHistory = 0;
        if (!quarterNow.getYearPart().equals(yearPart) || !quarterNow.getNum().equals(quarterNum)) {
            isHistory = 1;
        }
        Integer targetType = 0;//0校长指标，1老师指标
        boolean dateHistory = false;//按天看的历史数据
        Quarter searchQuarter = iQuarterService.getOneForYearAndNum(yearPart, quarterNum);
        //当前学期
        if (isHistory.equals(0)) {
            if (dateNow.equals(endDateFormat)) {
                dateHistory = false;
            } else {
                dateHistory = true;
            }
        } else {
            //非当前学期
            if (searchQuarter.getEndDate().equals(endDateFormat)) {
                //等于学期最后一天，校长指标
                targetType = 0;
            } else if (endDateFormat.isBefore(searchQuarter.getEndDate())) {
                //小于学期最后一天，按天看历史数据
                dateHistory = true;
            } else {
                //大于学期最后一天，老师指标
                targetType = 1;
            }
        }
        renewHistoryData.setIsHistory(isHistory);
        renewHistoryData.setDateHistory(dateHistory);
        renewHistoryData.setTargetType(targetType);
        return renewHistoryData;
    }

    /**
     * 续报率
     *
     * @param subjectsId
     * @param type
     * @param quarterNum
     * @param startDate
     * @param endDate
     * @param trackId
     * @return
     * @throws ParseException
     */
    @Override
    public List<ContinueInfo> getContinueFeeTeam(Integer yearPart, Integer quarterNum, String schoolId, String
            subjectsId, Integer type, String startDate, String endDate, String trackId, Integer lessonType, String
                                                         yearClassId, String classTypeId, String teamId, Integer trackType, Integer classify, AuthAdminContent
                                                         authAdminContent, LeadDataRs leadDataRs) throws ParseException {
        Quarter nextQuarter = CommonUtil.getNextQuarter(yearPart, quarterNum);
        Integer nextYearPart = nextQuarter.getYearPart();
        Integer nextQuarterNum = nextQuarter.getNum();
        LocalDate dateNow = LocalDate.now();
        int isHistorry = 0;
        if (dateNow.toString().equals(endDate)) {
            isHistorry = 1;
        }
        List<ContinueInfo> continueInfoList = teacherContinueInfoMapper.getRenewRecordTeam(schoolId, yearPart, quarterNum, nextYearPart, nextQuarterNum, subjectsId, type, startDate, endDate, lessonType, trackId, yearClassId, classTypeId, teamId, trackType, classify, isHistorry, authAdminContent, leadDataRs);
        HashMap<String, Integer> sumMap = new HashMap<>();
        for (ContinueInfo continueInfo : continueInfoList) {
            //百分比处理
            if (continueInfo.getStudentAllCount() > 0) {
                BigDecimal continueRate = new BigDecimal(continueInfo.getSchedulingCount()).divide(new BigDecimal(continueInfo.getStudentAllCount()), 4, RoundingMode.HALF_UP).multiply(new BigDecimal(100));
                continueInfo.setContinueRate(continueRate);
            } else {
                continueInfo.setContinueRate(new BigDecimal(0));
            }
            //数据相加处理，先记录，下面要放到父级
            Integer studentAllCount = sumMap.get(continueInfo.getTeamPid() + "StudentAllCount");
            Integer schedulingCount = sumMap.get(continueInfo.getTeamPid() + "SchedulingCount");
            Integer dateSchedulingCount = sumMap.get(continueInfo.getTeamPid() + "DateSchedulingCount");
            if (studentAllCount == null) {
                studentAllCount = 0;
            }
            if (schedulingCount == null) {
                schedulingCount = 0;
            }
            if (dateSchedulingCount == null) {
                dateSchedulingCount = 0;
            }
            sumMap.put(continueInfo.getTeamPid() + "StudentAllCount", continueInfo.getStudentAllCount() + studentAllCount);
            sumMap.put(continueInfo.getTeamPid() + "SchedulingCount", continueInfo.getSchedulingCount() + schedulingCount);
            sumMap.put(continueInfo.getTeamPid() + "DateSchedulingCount", continueInfo.getDateSchedulingCount() + dateSchedulingCount);
        }
        //拿出所有的战队列表
        List<TrackMarket> trackMarketList = iTrackMarketService.list(new QueryWrapper<TrackMarket>().eq("track_type", trackType).eq("classify", classify).eq("deleted", 0).eq("year_part", yearPart).eq("quarter_num", quarterNum));
        //创建一个空容器
        List<ContinueInfo> continueInfoArrayList = new ArrayList<>();
        for (TrackMarket trackMarket : trackMarketList) {
            ContinueInfo continueInfoNew = new ContinueInfo();
            if (trackMarket.getPid() != null && trackMarket.getPid() != 0L) {
                //不是父级的
                for (ContinueInfo continueInfo : continueInfoList) {
                    //对应战队id
                    if (continueInfo.getTeamId().equals(trackMarket.getId())) {
                        continueInfo.setTeamName(trackMarket.getTeamName());
                        continueInfoNew = continueInfo;
                        break;
                    }
                }
            } else {
                //父级处理
                continueInfoNew.setTeamId(trackMarket.getId());
                continueInfoNew.setTeamPid(trackMarket.getPid());
                continueInfoNew.setTeamName(trackMarket.getTeamName());
                //上面记录的数据，现在放进来
                Integer studentAllCount = sumMap.get(trackMarket.getId() + "StudentAllCount");
                Integer schedulingCount = sumMap.get(trackMarket.getId() + "SchedulingCount");
                Integer dateSchedulingCount = sumMap.get(trackMarket.getId() + "DateSchedulingCount");
                if (studentAllCount == null) {
                    studentAllCount = 0;
                }
                if (schedulingCount == null) {
                    schedulingCount = 0;
                }
                if (dateSchedulingCount == null) {
                    dateSchedulingCount = 0;
                }
                continueInfoNew.setStudentAllCount(studentAllCount);
                continueInfoNew.setSchedulingCount(schedulingCount);
                continueInfoNew.setDateSchedulingCount(dateSchedulingCount);
                //百分比处理
                if (continueInfoNew.getStudentAllCount() > 0) {
                    BigDecimal continueRate = new BigDecimal(continueInfoNew.getSchedulingCount()).divide(new BigDecimal(continueInfoNew.getStudentAllCount()), 4, RoundingMode.HALF_UP).multiply(new BigDecimal(100));
                    continueInfoNew.setContinueRate(continueRate);
                } else {
                    continueInfoNew.setContinueRate(new BigDecimal(0));
                }
            }
            continueInfoArrayList.add(continueInfoNew);
        }
        return getCategory(continueInfoArrayList, 0L);
    }


    public List<ContinueInfo> getCategory(List<ContinueInfo> list, Long pid) {
        List<ContinueInfo> result = new ArrayList<>();
        for (ContinueInfo continueInfo : list) {
            if (Objects.equals(continueInfo.getTeamPid(), pid)) {
                continueInfo.setChildren(getCategory(list, continueInfo.getTeamId()));
                result.add(continueInfo);
            }
        }
        return result;
    }

    @Override
    public IPage<ContinueInfo> getContinueFeeDetailTeam(IPage<?> iPage, Integer yearPart, Integer
            quarterNum, String schoolId, String subjectsId, Integer type, String startDate, String endDate, Integer
                                                                lessonType, String teacherId, String gradeId, String yearClassId, String classTypeId, String teamId, Integer
                                                                trackType, Integer classify) throws ParseException {
        Quarter nextQuarter = CommonUtil.getNextQuarter(yearPart, quarterNum);
        Integer nextYearPart = nextQuarter.getYearPart();
        Integer nextQuarterNum = nextQuarter.getNum();
        LocalDate dateNow = LocalDate.now();
        int isHistorry = 0;
        if (dateNow.toString().equals(endDate)) {
            isHistorry = 1;
        }
        return teacherContinueInfoMapper.getRenewRecordDetailTeam(iPage, schoolId, yearPart, quarterNum, nextYearPart, nextQuarterNum, subjectsId, type, startDate, endDate, lessonType, teacherId, gradeId, yearClassId, classTypeId, teamId, trackType, classify, isHistorry);
    }

    @Override
    public List<ContinueInfo> getRenewRecordDetailTeamTeacher(Integer yearPart, Integer quarterNum, String
            schoolId, String subjectsId, Integer type, String startDate, String endDate, String trackId, Integer
                                                                      lessonType, String yearClassId, String classTypeId, String teamId, Integer trackType, Integer
                                                                      classify, AuthAdminContent authAdminContent, LeadDataRs leadDataRs) throws ParseException {
        Quarter nextQuarter = CommonUtil.getNextQuarter(yearPart, quarterNum);
        Integer nextYearPart = nextQuarter.getYearPart();
        Integer nextQuarterNum = nextQuarter.getNum();
        LocalDate dateNow = LocalDate.now();
        int isHistorry = 0;
        if (dateNow.toString().equals(endDate)) {
            isHistorry = 1;
        }

        if (StringUtils.isNotBlank(teamId)) {
            String teamIdItem = trackMarketMapper.getTrackMarketChIdAll(Long.parseLong(teamId));
            if (StringUtils.isNotBlank(teamIdItem)) {
                teamId = teamIdItem;
            }
        }

        return teacherContinueInfoMapper.getRenewRecordDetailTeamTeacher(schoolId, yearPart, quarterNum, nextYearPart, nextQuarterNum, subjectsId, type, startDate, endDate, lessonType, trackId, yearClassId, classTypeId, teamId, trackType, classify, isHistorry, authAdminContent, leadDataRs);
    }

    private String getRenewRecordSql(DataSummaryList dataSummaryList, Integer nextYearPart, Integer
            nextQuarterNum, Integer i) {
        StringBuilder sql = new StringBuilder();
        sql.append("(SELECT * FROM (SELECT *,DENSE_RANK() OVER ( ORDER BY MAX( ");
        //1已排班；2总排班；3续报率
        if (dataSummaryList.getPaymentStatus() == 1) {
            sql.append(" date_scheduling_count ");
        }
        if (dataSummaryList.getPaymentStatus() == 2) {
            sql.append(" scheduling_count ");
        }
        if (dataSummaryList.getPaymentStatus() == 3) {
            sql.append(" continueRate ");
        }
        sql.append(" ) DESC ) AS ranking FROM ");

        sql.append("(SELECT" +
                " *," +
                " count(id) as student_all_count," +
                " getStaffNameForId(teacher_id) as teacher_name," +
                " getSchoolName(school_id) as school_name," +
                " SUM( CASE WHEN is_presort in(1,2,3) THEN 1 ELSE 0 END ) AS scheduling_count," +
                "(SUM( CASE WHEN is_presort in(1,2,3) THEN 1 ELSE 0 END ) / count( id ) * 100) AS continueRate, " +
                " SUM( CASE WHEN is_presort in(1,2,3) ");
        if (dataSummaryList.getStartDate() != null && dataSummaryList.getEndDate() != null) {
            sql.append("and presort_date BETWEEN '").append(dataSummaryList.getStartDate()).append("' AND '").append(dataSummaryList.getEndDate()).append("' ");
        }
        sql.append(" THEN 1 ELSE 0 END ) AS date_scheduling_count" +
                " FROM" +
                " (" +
                " SELECT" +
                " t01.id," +
                " t01.school_id," +
                " t03.year_class_id," +
                " t03.course_type_id," +
                " t01.student_id," +
                " t01.grade_id," +
                " t03.teacher_id," +
                " t03.`name` AS grade_name," +
                " t01.subjects_id," +
                " t01.lesson_type," +
                " t02.is_presort," +
                " DATE_FORMAT(t02.created_at, '%Y-%m-%d') as presort_date" +
                " FROM" +
                " (" +
                " SELECT" +
                " * " +
                " FROM" +
                " student_grade_view " +
                " WHERE" +
                " year_part = ").append(dataSummaryList.getYearPart()).append(" " +
                " AND quarter_num = ").append(dataSummaryList.getQuarterNum()).append(" " +
                " AND lesson_type = ").append(dataSummaryList.getLessonType()).append(" " +
                " AND deleted = 0 " +
                " AND STATUS = 1 " +
                " AND is_last = 1 " +
                " and is_makeup = 0" +
                " and (reading_status in(1,4,5,6) or (reading_status=3 and use_course_count>0))" +
                " and student_id not in(select student_id from renew_no_student where deleted=0 and year_part = ").append(dataSummaryList.getYearPart()).append(" and quarter_num = ").append(dataSummaryList.getQuarterNum()).append(")");
        if (i != null) {
            sql.append(" AND year_class_id = ").append(i).append(" ");
        } else {
            if (dataSummaryList.getYearClassId() != null) {
                sql.append(" and year_class_id IN (").append(dataSummaryList.getYearClassId()).append(") ");
            } else {
                if (dataSummaryList.getQuarterNum() == 2) {
                    sql.append(" and year_class_id < 9 ");
                }
                if (dataSummaryList.getQuarterNum() != 2) {
                    sql.append(" and year_class_id < 10 ");
                }
            }
        }
        sql.append(" GROUP BY" +
                " school_id," +
                " student_id," +
                " teacher_id," +
                " subjects_id " +
                " ) AS t01" +
                " LEFT JOIN (" +
                " SELECT" +
                " * " +
                " FROM" +
                " student_grade " +
                " WHERE" +
                " year_part = ").append(nextYearPart).append(" " +
                " AND quarter_num = ").append(nextQuarterNum).append(" " +
                " AND lesson_type = ").append(dataSummaryList.getLessonType()).append(" " +
                " AND deleted = 0 " +
                " AND is_presort in(1,2,3) " +
                " GROUP BY" +
                " student_id," +
                " subjects_id " +
                " ) AS t02 ON t01.student_id = t02.student_id " +
                " AND t01.subjects_id = t02.subjects_id" +
                " LEFT JOIN grade AS t03 ON t01.grade_id = t03.id " +
                " ) AS t" +
                " where 1=1");
        if (dataSummaryList.getTrackId() != null) {
            sql.append(" and teacher_id in(select sourse_id from track_detail where deleted = 0 and track_id = ").append(dataSummaryList.getTrackId()).append(")");
        }
        if (dataSummaryList.getSubjectsId() != null) {
            sql.append(" and subjects_id=").append(dataSummaryList.getSubjectsId());
        }
        if (dataSummaryList.getSchoolId() != null) {
            sql.append(" and school_id in(").append(dataSummaryList.getSchoolId()).append(")");
        }
        if (i != null) {
            sql.append(" AND year_class_id = ").append(i).append(" ");
        } else {
            if (dataSummaryList.getYearClassId() != null) {
                sql.append(" and year_class_id in(").append(dataSummaryList.getYearClassId()).append(")");
            }
        }
        if (dataSummaryList.getClassTypeId() != null) {
            sql.append(" and course_type_id in(").append(dataSummaryList.getClassTypeId()).append(")");
        }
        sql.append(" GROUP BY" +
                " teacher_id)");
        sql.append(" AS fff ");
        sql.append("GROUP BY teacher_id");
        sql.append(" ORDER BY ranking ASC ) AS ttt WHERE ranking <= ").append(dataSummaryList.getSeeRows()).append(") ");
        return sql.toString();
    }

    public List<ContinueInfo> getDataSummaryRenewRecord(DataSummaryList dataSummaryList) {
        Quarter nextQuarter = CommonUtil.getNextQuarter(dataSummaryList.getYearPart(), dataSummaryList.getQuarterNum());
        Integer nextYearPart = nextQuarter.getYearPart();
        Integer nextQuarterNum = nextQuarter.getNum();

        StringBuilder sql = new StringBuilder();
        if (dataSummaryList.getIsType() == 1) {
            for (int i = 0; i < ConfigData.yearClassNameArr.length; i++) {
                if (sql.length() > 0) {
                    sql.append("union all");
                }

                sql.append(getRenewRecordSql(dataSummaryList, nextYearPart, nextQuarterNum, i));
            }
        } else {
            sql.append(getRenewRecordSql(dataSummaryList, nextYearPart, nextQuarterNum, null));
        }
        // studentAllCount 总应缴; bigFifteen 总已缴; littleFifteen 总未缴; payNum 已缴; 总已缴 / 总应缴 = percentage 缴费率
        List<ContinueInfo> dataSummaryRenewRecord = orderDetailMapper.getDataSummaryRenewRecord(sql.toString());
        for (ContinueInfo continueInfo : dataSummaryRenewRecord) {
            if (continueInfo.getStudentAllCount() > 0) {
                BigDecimal continueRate = new BigDecimal(
                        continueInfo.getSchedulingCount()
                )
                        .divide(new BigDecimal(continueInfo.getStudentAllCount()), 4, RoundingMode.HALF_UP)
                        .multiply(new BigDecimal(100));
                continueInfo.setContinueRate(continueRate);
            } else {
                continueInfo.setContinueRate(new BigDecimal(0));
            }
        }
        return dataSummaryRenewRecord;
    }

    @Override
    public List<RenewClassRecord> getPayFeeByTeacherIdList(String schoolId, Integer yearPart, Integer
            quarterNum, String subjectsId, Integer type, String startDate, String endDate, String trackId, Integer
                                                                   lessonType, String yearClassId, String classTypeId, Integer periodsNum, String name, String
                                                                   startGradeCount, String endGradeCount) throws ParseException {

        Quarter quarterNow = iQuarterService.getNowQuarter();

        //期数，1期为45，2期为90
        Integer feeCourseNum = this.getCourseNumForPeriods(periodsNum);

        if (yearPart == null) {
            yearPart = quarterNow.getYearPart();
        }
        if (quarterNum == null) {
            quarterNum = quarterNow.getNum();
        }
        RenewHistoryData renewHistoryData = this.getHistoryData(yearPart, quarterNum, endDate, quarterNow);
        //是否查看历史的，1是，0否，查看历史的要使用(整个学期)历史表
        Integer isHistory = renewHistoryData.getIsHistory();
        Integer targetType = renewHistoryData.getTargetType();//0校长指标，1老师指标

        Integer payYearPart = yearPart;
        Integer payQuarterNum = quarterNum;

        Integer searchYearAndQuarter = Integer.parseInt(yearPart + "" + quarterNum);
        Integer nextYearAndQuarter = 0;
        if (isHistory.equals(1) && targetType.equals(1)) {
            Integer quarterId = iQuarterService.getIdForYearPartAndNum(yearPart, quarterNum);
            Quarter nextQuater = iQuarterService.getQuarterMaxForId(quarterId + 1);//获取当前学期的下个学期后的学期
            if (nextQuater != null) {
                nextYearAndQuarter = Integer.parseInt(nextQuater.getYearPart() + "" + nextQuater.getNum());
            }
            payYearPart = quarterNow.getYearPart();
            payQuarterNum = quarterNow.getNum();
        }

        List<RenewClassRecord> renewClassRecordList = new ArrayList<>();

        renewClassRecordList = orderDetailMapper.getPayFeeByTeacherIdList(schoolId, yearPart, quarterNum, subjectsId, type, startDate, endDate, trackId, isHistory, lessonType, searchYearAndQuarter, nextYearAndQuarter, payYearPart, payQuarterNum, yearClassId, classTypeId, feeCourseNum, periodsNum, name, startGradeCount, endGradeCount);


        if (type == 6 && StringUtils.isBlank(schoolId)) {

            List<RenewClassRecord> collectList = new ArrayList<>();

            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("year_part", yearPart);
            queryWrapper.eq("quarter_num", quarterNum);
            queryWrapper.eq("pid", 0);
            List<SchoolQuarter> schoolQuarterList = iSchoolQuarterService.list(queryWrapper);

            for (SchoolQuarter schoolQuarter : schoolQuarterList) {
                RenewClassRecord practicePlanStaff = new RenewClassRecord();
                practicePlanStaff.setSchoolId(schoolQuarter.getSchoolId());
                practicePlanStaff.setSchoolName(schoolQuarter.getSchoolName());
                practicePlanStaff.setSchoolPid(schoolQuarter.getPid());
                practicePlanStaff.setStudentAllCount(0);
                practicePlanStaff.setBigFifteen(0);
                practicePlanStaff.setLittleFifteen(0);
                practicePlanStaff.setPayNum(0);

                collectList.add(practicePlanStaff);
            }

            for (RenewClassRecord practicePlanStaff : collectList) {
                List<RenewClassRecord> childRates = new ArrayList<>();
                for (RenewClassRecord planStaff : renewClassRecordList) {
                    if (practicePlanStaff.getSchoolId().equals(planStaff.getSchoolId()) || practicePlanStaff.getSchoolId().equals(planStaff.getSchoolPid())) {
                        childRates.add(planStaff);
                        if (planStaff.getStudentAllCount() != null) {
                            practicePlanStaff.setStudentAllCount(practicePlanStaff.getStudentAllCount() + planStaff.getStudentAllCount());
                        }
                        if (planStaff.getBigFifteen() != null) {
                            practicePlanStaff.setBigFifteen(practicePlanStaff.getBigFifteen() + planStaff.getBigFifteen());
                        }
                        if (planStaff.getLittleFifteen() != null) {
                            practicePlanStaff.setLittleFifteen(practicePlanStaff.getLittleFifteen() + planStaff.getLittleFifteen());
                        }
                        if (planStaff.getPayNum() != null) {
                            practicePlanStaff.setPayNum(practicePlanStaff.getPayNum() + planStaff.getPayNum());
                        }
                    }
                }
                practicePlanStaff.setChildren(childRates);
            }

            renewClassRecordList = collectList;

        }


        return renewClassRecordList;
    }

    @Override
    public List<ContinueInfo> getContinueFeeByTeacherIdList(Integer yearPart, Integer quarterNum, String
            schoolId, String subjectsId, Integer type, String trackId, Integer lessonType, String yearClassId, String
                                                                    classTypeId, String name, String startGradeCount, String endGradeCount) throws ParseException {
        Quarter nextQuarter = CommonUtil.getNextQuarter(yearPart, quarterNum);
        Integer nextYearPart = nextQuarter.getYearPart();
        Integer nextQuarterNum = nextQuarter.getNum();

        List<ContinueInfo> continueInfoList = teacherContinueInfoMapper.getContinueFeeByTeacherIdList(schoolId, yearPart, quarterNum, nextYearPart, nextQuarterNum, subjectsId, type, lessonType, trackId, yearClassId, classTypeId, name, startGradeCount, endGradeCount);


        if (type == 6 && StringUtils.isBlank(schoolId)) {

            List<ContinueInfo> collectList = new ArrayList<>();

            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("year_part", yearPart);
            queryWrapper.eq("quarter_num", quarterNum);
            queryWrapper.eq("pid", 0);
            List<SchoolQuarter> schoolQuarterList = iSchoolQuarterService.list(queryWrapper);

            for (SchoolQuarter schoolQuarter : schoolQuarterList) {
                ContinueInfo practicePlanStaff = new ContinueInfo();
                practicePlanStaff.setSchoolId(schoolQuarter.getSchoolId());
                practicePlanStaff.setSchoolName(schoolQuarter.getSchoolName());
                practicePlanStaff.setSchoolPid(schoolQuarter.getPid());
                practicePlanStaff.setStudentAllCount(0);
                practicePlanStaff.setSchedulingCount(0);
                practicePlanStaff.setDateSchedulingCount(0);

                collectList.add(practicePlanStaff);
            }

            for (ContinueInfo practicePlanStaff : collectList) {
                List<ContinueInfo> childRates = new ArrayList<>();
                for (ContinueInfo planStaff : continueInfoList) {
                    if (practicePlanStaff.getSchoolId().equals(planStaff.getSchoolId()) || practicePlanStaff.getSchoolId().equals(planStaff.getSchoolPid())) {
                        childRates.add(planStaff);
                        if (planStaff.getStudentAllCount() != null) {
                            practicePlanStaff.setStudentAllCount(practicePlanStaff.getStudentAllCount() + planStaff.getStudentAllCount());
                        }
                        if (planStaff.getSchedulingCount() != null) {
                            practicePlanStaff.setSchedulingCount(practicePlanStaff.getSchedulingCount() + planStaff.getSchedulingCount());
                        }
                        if (planStaff.getDateSchedulingCount() != null) {
                            practicePlanStaff.setDateSchedulingCount(practicePlanStaff.getDateSchedulingCount() + planStaff.getDateSchedulingCount());
                        }
                    }
                }
                practicePlanStaff.setChildren(childRates);
            }

            continueInfoList = collectList;
        }

        return continueInfoList;
    }


}
